You are here
Home > Kotlin

Kotlin Secondary Constructor

this and super keyword

Kotlin Secondary Constructor

In previous post we discussed kotlin classes and primary constructor. And in this post we will discuss how to defined secondary constructor in kotlin classes.

Kotlin Secondary Constructor

  • For declaration of secondary constructor use constructor keyword:

class Employee
{
                       constructor(parent: Employee)
{
parent.children.add(this)
}
}

  • If the class has a primary constructor, each secondary constructor needs to delegate to the primary constructor, either directly or indirectly through another secondary constructor(s). for delegation to another constructor of the same class is done using this keyword:

             class Employee(val name: String)
{
                      constructor(name: String, parent: Person) : this(name) {
parent.children.add(this)
}
}

Example: use of secondary constructor

class phonewithconst()
{
var Price:Double?=null;
var Storage:String?=null;
constructor(Company:String,Price:Double, Storage:String):this()
{
println(“Company=”+Company);
println(“Price=”+Price);
println(“Storage=”+Storage);
this.Price=Price;
this.Storage=Storage;
}
fun getprice():Double?
{
return this.Price;
}
fun getstorage():String?
{
return this.Storage;
}
}
fun main(args:Array<String>)
{
var s=phonewithconst(“XYZ”,16000.0,”16GB”);
println(“XYZ”);
println(“Price=”+s.getprice());
println(“Storage=”+s.getstorage());
var r=phonewithconst(“ABC”,9000.0 ,”34Gb”);
println(“ABC”);
println(“Price=”+r.getprice());
println(“Storage=”+r.getstorage());
}
output:

Explanation:

In this example, we create a secondary constructor do we have to delegate the primary constructor using this keyword.

this and super keyword

  • this keyword is used in same class to refers to the functions, variables that are in the same class.
  • Super keyword is used in different class to refers to the functions, variables that are in the different class.

Example:

open class X2()
{
fun get():Unit
{
println(“Java”);
}
fun display():Unit
{
this.get();
println(“display function”);
}
}
class Y2():X2()
{
fun put():Unit
{
super.display();
super.get();
println(“Kotlin”);
}
}
fun main(args:Array<String>)
{
var objy2=Y2();
objy2.put();
}

output:

Explanation:

In this example we create two functions in class X2 get() and display(). In display() function we call get() function using this keyword. In class Y2 we create a put() function. We call get() and display() function using super keyword from put() function.

Keep Visiting TechwithR.com for more upcoming top technical articles and also see my new blog Mag4info. and for kotlin tutorial also see my blog kotlin category.

For online shopping visit BestBuy101.com
You can also by SQL 70-761 book write by me from Amazon.
You can also by Kotlin Book write by me from Amazon.

Leave a Reply

Top