Kotlin - Class & Objects

Kotlin supports both Object Oriented and Functional Programming As we know in Object Oriented Program, class is nothing but a blue print of an entity, where as Object is its State. Object inclused state and behaviour of state.

Class ClassA
{
    // class Body
 }



Let's check below examples

How do i create a class object in Kotlin

Car is an Object

Where State of Car are

Speed
Gear
Behaviours are
Change Gear
Go fast/slow



Lets Create a Object with its state and Behaviour
class Car {

// property (data member)
private var Speed: Int = 30

// member function
fun goSpeed() {
 Speed = 60
}

// member function
fun goSlow() {
 Speed = 20
}
}


In above we created a class with name Car

Car contains property is speed and we can change the behavoiur of the car by memeber functions
goSpeed() and goSlow()


Object Creation

When we created a class, to access/update the state/behaviour of the class we need to create an object to that class

We can check below how to create an object

class Car {

// property (data member)
private var Speed: Int = 30

// member function
fun goSpeed() {
Speed = 60
}

// member function
 fun goSlow() {
     Speed = 20
 }
}
fun main(args:Array){
    val obj=Car()
}
                                

Here obj is object for the class Car, create object by calling the call with open close braces
(Car())

Like java, in kotlin not required new key word

Subscribe For Daily Updates