Kotlin Inheritance

Kotlin Inheritance – Inheritance is one of the powerful Object Oriented Programming concept. Inheritance is a mechanism in which a class can extend the behaviour of another class.

  • One class can inherit another class.
  • The class being inherited is called Parent (or Super) class and the class that is inheriting Parent Class is called Child (or Sub) class.
  • Child classes inherit variables and methods of Parent class.
  • A Parent class can have any number of Child classes, but a Child Class can have only one Parent class.

Where to identify and use inheritance in Kotlin programming?

Inheritance could be used where a group of classes would have some of the behaviours in common. For example : Student and Teacher are two different class of persons, but they belong to Person category. Here Student and Teacher could have their own specific behaviours like activity(), profession(), but they have some behaviours like eating, sleeping, etc. in common.

While designing an application containing Student, Teacher, etc., if we create a Parent class called Person, we could have the common behaviours of Student, Teacher, etc., in Person and any specific behaviours in their own class definition.

Syntax – Kotlin Inheritance

Following is the syntax to declare a class to inherit another class in Kotlin.

Example – Kotlin Inheritance

Following example demonstrates Inheritance in Kotlin. We shall take the above example scenario of Student, Teacher : Person.

When the above program is run

Takeaways from the above Example

  1. Variables : name, role belong to Person Class. But they are accessible to Student and Teacher classes because of inheritance.
  2. Methods : eat(), sleep() belong to Person Class. But they are accessible to Child classes because of inheritance.
  3. Observe the primary constructors of Parent class and Child class. Child class does not have var keyword for variable : name in the definition, hence it refers to the variable of Parent class. This is kind of variable overloading. Behaviours could also be overwritten. We shall learn about method overloading in next tutorial.
  4. The inheritance definition in Child class should at-least provide primary constructor of Parent Class. Student, while inheriting Person, provided values for primary constructor (role, name).
  5. The code maintenance for the methods : eat() and sleep() becomes simple, because there is only one place in the code where you need to change if there is a requirement to alter the behaviour.

Conclusion :

In this Kotlin TutorialKotlin Inheritance, we have learnt what Inheritance mean in Object Oriented Programming, how to implement inheritance in Kotlin programming with an example Kotlin program.