Default constructor

The following class declaration is an example of a default constructor, when all properties of the class are directly initialized in the class body:

class Person {
var name: String = "Abid"
var age : Int = 40
var height : Double = 6.0
}
val person = Person()

If you don't create a constructor for your class, Kotlin creates a default constructor automatically. The default constructor is a zero-argument constructor, in which all properties of the Person class contain some fixed initial values. The default constructor is not a good approach for object-creation. The object may have different values during its lifetime, but it will always have the same initial value at the time of creation.

In the following example, a Person class contains fixed initial values of each attribute:

class Person {
var name: String = "Abid"
var age : Int = 40
var height : Double = 6.0
}

fun main(args: Array<String>) {

val p1 = Person()
println("Name ${p1.name}, Age ${p1.age} Height ${p1.height}")

val p2 = Person()
println("Name ${p2.name}, Age ${p2.age} Height ${p2.height}")

p2.name = "Khan"
p2.age = 31

println("Name ${p2.name}, Age ${p2.age} Height ${p2.height}")
}

All objects created by this method contain similar values:

As we can see in this output, there are two instances of the Person class, p1 and p2, and both instances contain similar values. To assign different values to different objects, we can use a primary constructor.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.191.233.43