Multilevel inheritance

When a class is derived from a class that is already derived from another class, this inheritance is called multilevel inheritance. This refers to a situation where at least one class has more than one parent class. As we can see in the following diagram, B is derived from A, and C is derived from B. C not only contains the properties and behaviors of B, but also from class A, as well as its own. Let's create a superclass, Person, a derived class, Employee, and another derived class, Programmer:

The Person class contains one property, name, and two behaviors, sleep and speak. The Employee class inherits everything from the Person class. It has one property, company, and one behavior, work. Finally, the Programmer child class contains all the behaviors and properties from its parent classes and has two functions, code and the overridden sleep function:

open class Person (val name : String){
fun speak(){
println("My name is $name")
}

open fun sleep(){
println("I like to sleep 7 hours a day")
}
}

open class Employee(name: String, val company : String) : Person(name) {
fun work(){
println("I work for $company")
}
}

class Programmer(name: String, company: String) : Employee(name, company){
fun code(){
println("Coding is my passion")
}

override fun sleep(){
println("I like to sleep when i get a chance.")
}
}

fun main(args: Array<String>) {

val coder = Programmer("Abid", "Kotlin Conf")
coder.speak()
coder.work()
coder.code()
coder.sleep()
}

Let's run this code and function call:

The Person class contains two functions, speak and sleep. The Employee class contains three functions, two from the Person class and work, which is its own. The Programmer class contains two of its own functions, code and sleepsleep is an overridden function from its grandparent's Person class:

val coder = Programmer("Abid","Kotlin Conf")

It is very important to know which version of the function will be called:

  • coder.speak(): The coder instance calls the Person class' speak function
  • coder.sleep(): The coder instance calls the Programmer class' sleep function
  • coder.work(): The coder instance calls the Employee class' work function
  • coder.code(): The coder instance calls the Programmer class' code function

When a function is called, Kotlin searches from bottom to top. It looks in the lowest class in the hierarchy first and moves upward until it finds the function.

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

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