Abhas Kumar
Android & Kotlin with the eyes of Abhas

Android & Kotlin with the eyes of Abhas

Kotlin Constructor - Abhas Kumar

When I was studying Constructor I was bombarded with multiple questions in my mind like:

  1. What actually Constructor is?
  2. Why there is need of Constructor?
  3. Can't we create objects without Constructor?
  4. Why visibility modifiers are changing it's naming conventions?

Everywhere I found how to write constructors and how it helps in initializing the object but still my questions were unanswered and as a beginner I needed to give answers to myself. So keeping this situation in my mind I am writing this article so that it can help any newbie to understand the concept of constructors. So now let's understand step by step.

Let's start with defining a class. General way of creating a class is

class Vehicle{

}

Let's create an instance of Vehicle class or say create an object of Vehicle class.

fun main(){
       val vehicle = Vehicle()
}

That's it we have created an object of Vehicle. ' vehicle ' is an object identifier referencing to Vehicle object. Now if you know a bit about Objects and Classes you know there is no meaning of it without any state and behavior. We create a class to store state and behavior for a particular thing so that we can create multiple instances and play around it as per our need. Let's define some properties in Vehicle class to make it meaningful.

class Vehicle{
            var name = " BMW "      
            var model = " BMW X5 " 

           // We have defined a property also known as state and initializing it.
}

Now let's create an object and access it's properties and make some changes around it.

fun main(){
    val vehicle = Vehicle()
    println(vehicle.name)  // It will access the property name and print BMW
    println(vehicle.model) // It will access the property model and print BMW X5

}

Let's make some changes in Vehicle properties according to object created.

fun main(){
    val vehicle = Vehicle()
    vehicle.name = "Toyota"  // object identifier can access the property using '.' notation.
    vehicle.model = "Etios"
    println(vehicle.name) // prints Toyota
    println(vehicle.model) // prints Etios

}

Now here comes the concept of Constructor. Constructor helps to initialize the properties of objects. We can initialize a new object by passing information to a constructor unlike we have done in above examples. In above example we initialized the properties in class and it limited the way we can create objects and initialize properties. Let's see how we can use constructors to initialize object:

class Vehicle(name:String,model:String) {

    var name = name
    var model = model

}

Let's create an object of Vehicle class:

fun main(){
        val vehicle = Vehicle("BMW","BMW X5")
        println("Vehicle name is ${vehicle.name} & vehicle model is ${vehicle.model}")
    }

Now you can see object vehicle is initialized with constructor arguments and we don't need to initialize properties in Vehicle class and neither we needed to access properties after object creation to make it meaningful. We can assign any value we want in order at the time of object initialization with the help of constructors. Constructor is like member function in class. Constructor allows us to put some logic beyond properties and functions using init block:

class Vehicle(name1:String,model1:String) {

    var name = name1
    var model = model1
    init {
        println("Vehicle name is $name & vehicle model is $model")
    }
}



    fun main(){
        val vehicle = Vehicle("BMW","BMW X5")
    }

We can see we have used some of our own logic in init block and it will be executed at the time of object initialization.

So overall Constructor provides us robust way to initialize object and it ensures:

  1. Additional logic execution while object creation
  2. Dynamic properties initialization
  3. More control over data manipulation

Of course there are many things we could have discussed like:

  1. We can use constructor parameters like object properties
  2. We can use Secondary constructor
  3. Constructor overloading

But I wanted to keep this article limited to Constructor basic understanding and why it is good option to use constructors while object creation.

Thanks!

 
Share this