In this section, we will learn the relation between inheritance and constructors of classes that are involved in the inheritance.
Parent Initialization and Constructors in Kotlin Inheritance
When a child class inherits from a parent class, it is important to pass the right arguments to the constructor of that parent class if the parent class has an explicitly defined constructor (either primary or secondary constructor). Otherwise, we will get an error if we don’t set the arguments of the parent class.
For a parent class that has more than one constructor, it is up to us to choose the right one in the child class to call but, we must call at least one and set its arguments as well.
Example: initializing constructors in Kotlin inheritance
open class Person{ var firstName:String var lastName:String constructor (firstName:String, lastName:String){ this.firstName = firstName this.lastName = lastName } } class Employee (firstName:String, lastName:String, var company:String): Person(firstName, lastName){ } fun main(){ var emp = Employee("John","Doe","Apple") println(emp.firstName) println(emp.lastName) println(emp.company) }
Output:
John Doe Apple
How does initialization work in Kotlin inheritance?
In this example, we can see the Employee
class inherited from the Person class. This parent class has one secondary constructor and so we’re now responsible for passing enough arguments (two in this case) for that constructor when we’re making the Employee class to extend to the Person class.
For this example, we’ve used the parameters of the Employee class as the arguments for the constructor of the Person class. But of course we could also pass an explicitly set values for the Person constructor as well.
For example:
class Employee (var company:String): Person("John", "Doe"){ }
But it’s much better to let the values of the parent constructor (the Person class in this case) be set dynamically and that is by passing the parameters of the child class as the argument for the constructor of the parent class.