OOPs Concepts(Examples in Kotlin)

The Oops concepts are the foundation when you want to create a good application and want to scale it in the future and want reusable and clean code, In Oops concepts we divide a bigger problem into smaller entities and relate them with real-time scenarios and solve them separately and combine them again in a structured manner.

Let's see Each concept in detail with real-time examples

1. Object:

An Object is an entity that has a state and behavior.

State: The attribute of an object is called state such as an Engineer has firstName,lastName,empId, etc.

Behavior: The work can be done by engineers such as Create An application, or Construct a road, Create an engine, Programing for semiconductors, etc.

In the real world: We all are the object of the Human class

Or we can say in a simple real-time programming world An object is an instance of a class.

Example:

data class Student(
//Properties or state
val rollNumber: Int,
val name: String,
val phoneNumber: String
){
//Behaviour
fun attendingLectures(student: Student){
println("Student: ${student.name} is attending the class")

}
}

This is the Student class which is having some properties and behavior.

fun main() {
//adding attributes to the object of student class
var student1 = Student(1, "S1", "9876543210")
var student2 = Student(2, "S2", "98765430910")
println("Student: $student1")
println("Student: $student2")
//performing the behaviour
student1.attendingLectures(student1)

}

Here s1 and s2 are 2 objects which are having some properties defined by the class and student s1 is performing the behavior.

2. Class:

A class is a group of similar types of objects or Entities.

In the Real world, we can say Animal is a class and different types of Animal are objects of the class.

Class is only a logical component and not a physical entity.

Such as Dog, Cat, Lion, etc are objects of the Animal class.

In Programming “A class is a collection of objects which has state and behavior”

Class is a collection of data members and functions.

A Class is a blueprint by which we can create the objects.

3. Inheritance:

Inheritance is one of the Basic Concepts of OOPs in which one object acquires the properties and behaviors of the parent object. It’s creating a parent-child relationship between two classes. It offers a robust and natural mechanism for organizing and structuring any software. It provides code reusability.

The idea behind inheritance in Java is that you can create new classes that are built upon existing classes. When you inherit from an existing class, you can reuse methods and fields of the parent class. Moreover, you can add new methods and fields in your current class also.

Types of Inheritance:

Relationships in Oops:

1. IS-A (Inheritance) ->(Classes will be Tightly coupled)

open class Car {

}

class Maruti : Car(){

}

Here Car and Maruti are in an IA-A relationship.

So we can say Maruti IS-A Car.

Both are tightly coupled so anything changes in a superclass can be affected child class as well.

2.HAS-A (Association) -> It has 2 types

1. Aggregation (Weak Bonding):

class MusicPlayer {
}
class Car {
var musicPlayer = MusicPlayer()
}

Here we have 2 classes which are in HAS-A Relationship.

So we can say The Car HAS-A MusicPlayer

Notice that the car and music player are separate entities both can work without each other so that's why it has weak bonding.

2. Composition (Strong Bonding):

class Engine {
}

class Car {
var engine = Engine()
}

Car HAS-A Engine

Notice that the car and engine are the combinations to run the car so both are in strong bonding, Both need to start the car.

4. Encapsulation:

Encapsulation is an object-oriented procedure of combining the data members and member functions of the class inside the user-defined class.

It has to have private data members and should have public getter methods so that the logic should be private to class and results can be gotten from outsiders.

We can create a fully encapsulated class in Java by making all the data members of the class private. Now we can use setter and getter methods to set and get the data in it.

class Account {

private var interestRate: Double = 5.0
private var finalAmount: Double = 0.0

public fun setAmount(amount: Double, durationYear: Int) {
finalAmount = (amount * interestRate * durationYear) / 100
}

public fun getFinalAmount(): Double {
return finalAmount
}

}

Here we have an accounting class and we want to calculate the interest on the amount.

We only expose setAmount function where the user can set the amount and from getFinalAmount function, the user can get the amount, Rest of the logic is hidden from the user’s access.

We have a read-only class (If we want to create a read-only class so we can use encapsulation)

This is the way of data hiding.

5. Abstraction:

Data Abstraction is the process of hiding certain details and showing only essential information to the user.
Abstraction can be achieved with either Abstract classes (0 to 100%) or Interface (100%)

Abstract Class:

A class that is declared as abstract is known as an abstract class. It can have abstract and non-abstract methods. It needs to be extended and its method implemented. It cannot be instantiated. It can have a constructor as well.

abstract class Car {

abstract fun start()

fun run() {
println("Car is running")
}

}

Here we have A abstract function and a concreate function, Now any class which will extend the car class needs to provide the detailed implementation of the start function and they can use the run function as it is.

Interface:

The interface is a blueprint of the class which will have a set of functions. Any class which implements the interface needs to provide the implementation of the functions.

interface Car {
abstract fun start()
}

class MarutiCar : Car{
override fun start() {
TODO("Not yet implemented")
}

}

Like abstract classes, interfaces cannot be used to create objects

Interface methods do not have a body — the body is provided by the “implement” class

On implementation of an interface, you must override all of its methods

Interface methods are by default abstract and public

An interface cannot contain a constructor (as it cannot be used to create objects)

Java does not support “multiple inheritances”. However, it can be achieved with interfaces, because the class can implement multiple interfaces.

Types of interface:

  1. Functional Interface: An interface that has only 1 function in it.
  2. Marker Interface: An Interface that has no method in it.

6. Polymorphism:

The word polymorphism means having many forms. Many operations can be performed by the objects at a different instance of use.

A person at the same time can have different characteristics. A man at the same time is a father, a husband, and an employee. So the same person possesses different behavior in different situations. This is called polymorphism.

There are two types of polymorphism:

compile-time polymorphism and runtime polymorphism

Compile-time-polymorphism:

The behavior of the object is decided at the time of compilation only.

This can be achieved by Method Overloading

Method overloading is a concept where more than 1 method will have the same name and different parameters.

Functions can be overloaded by a change in the number of arguments or/and a change in the type of arguments.

class Calculation {    fun addNumbers(n1: Int, n2: Int): Int {
return n1 + n2;
}
fun addNumbers(n1: Int, n2: Int, n3: Int): Int {
return n1 + n2 + n3
}
}

We have 2 functions with the same name but different parameters.

Run-time-polymorphism:

The behavior of the objects gets decided at the time of creating the object.

It is a process in which a function call to the overridden method is resolved at Runtime. This type of polymorphism is achieved by Method Overriding.

open class Parent {
open fun age(): Int {
return 66
}
}
class Child : Parent() {
override fun age(): Int {
return 24
}
}
fun main() { var person = Parent()
person.age()
var person1 = Child()
person1.age()

}

Here we have 2 classes in an IS-A(Inheritance) relationship and having age function which subclass is overriding and providing own details.

--

--

--

Senior Android App Developer | Startup | Product base | Java | Kotlin | MVVM | Architecture components | Android Blogger

Love podcasts or audiobooks? Learn on the go with our new app.

Recommended from Medium

Deep dive in to BeanUtilsBean .populate

Firebase Cloud Messaging(FCM) android implementation — Part 1

Create A Space Shooter Game | Egretia Engine Tutorial For Beginners Part 4

PCOMP Final: Arduino Drum Set

Witchcraft: the magic of math, functional programming, and community

Why I didn’t hear about Product Management in college

Meta / Google Interview Question — LeetCode 1087

Top 5 EMMET Shortcut For HTML

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Aalishan Ansari

Aalishan Ansari

Senior Android App Developer | Startup | Product base | Java | Kotlin | MVVM | Architecture components | Android Blogger

More from Medium

Primer for String on Java/Kotlin

GRASP Principles for Android Development — Information Expert | Part 1

Introduction to Android Unit Testing using Kotlin and JUnit

Quest to a refined Outdoor Experience Android App — Part 5: Feed using Paging 3