Kotlin - Inheritance Example

Inheritance is an important feature of object-oriented programming language. Inheritance allows inheriting the feature of an existing class (or base or parent class) to a new class (or derived class or child class).

The concept of inheritance is allowed when two or more classes have the same properties. It allows code reusability. A derived class has only one base class but may have multiple interfaces whereas a base class may have one or more derived classes.

In Kotlin, the derived class inherits a base class using : operator in the class header (after the derived class name or constructor).
open class Base(p: Int){  
  
}  
class Derived(p: Int) : Base(p){  
  
}  

Kotlin Inheritance Example

package net.javaguides.kotlin.examples

open class Employee(name: String, age: Int, salary: Float) {
    init {
        println("Name is $name.")
        println("Age is $age")
        println("Salary is $salary")
    }
}

class Programmer(name: String, age: Int, salary: Float): Employee(name, age, salary) {
    fun doProgram() {
        println("programming is my passion.")
    }
}

class Salesman(name: String, age: Int, salary: Float): Employee(name, age, salary) {
    fun fieldWork() {
        println("travelling is my hobby.")
    }
}

fun main(args: Array < String > ) {
    val obj1 = Programmer("Ramesh", 25, 40000 f)
    obj1.doProgram()
    val obj2 = Salesman("Vijay", 24, 30000 f)
    obj2.fieldWork()
}
Output:
Name is Ramesh.
Age is 25
Salary is 40000.0
programming is my passion.
Name is Vijay.
Age is 24
Salary is 30000.0
travelling is my hobby.

Kotlin open keyword

As Kotlin classes are final by default, they cannot be inherited simply. We use the open keyword before the class to inherit a class and make it to non-final. For example:
open class Employee(name: String, age: Int, salary: Float) {
    init {
        println("Name is $name.")
        println("Age is $age")
        println("Salary is $salary")
    }
}


Comments