Kotlin OOP - Parenthesis After Parent Class ?

·

3 min read

When I was learning Kotlin OOP, I was wonder why is parenthesis behind the name of parent class is needed when extending a class in Kotlin?

For example: If we create a Animal parent class:

open class Animal()

Then we make child class Cat extend Animal

// Need to put () behind animal
class Cat(var breed: String) : Animal()

You will notice that we have to put a parenthesis after Animal class. However, if we do this in Java. Parenthesis is not needed:

class Cat extends Animal {
    String breed;

    public Cat(String name) {
        super();
        this.breed = breed;
    } 
}

The reason behind it is quite simple. When we try to extend a class in Java, it is required to invoke parent constructor in the constructor of child class. However, the main constructor of Kotlin doesn't have function body. Therefore, when declaring inheritance, We place parenthesis after the name of parent class to invoke parent's constructor.

If we add parameter to the main constructor of parent class, we have to add it to the constructor of child class and do constructor invocation after extension syntax:

open class Animal(var age: Int)

class Cat(var breed: String, age: Int) : Animal(age)

We can do constructor invocation of parent class after the main constructor of child class. How about secondary constructor?

In Kotlin, for secondary constructor of child class, it is required to invoke the main constructor.

class Cat(var breed: String, age: Int) : Animal(age) {
    constructor(): this("Ragdoll", 3) {
    }
}

One last thing, Kotlin allows us to create secondary constructor without using primary constructor. In this case, we have to use super keyword to achieve calling the constructor of parent class:

class Cat : Animal {
    constructor(age: Int): super(age) {
    }
}

I hope you learn something from my article. Thanks for reading : )

Reference: 《第一行代码》- 郭霖