Overriding Properties & Functions in Kotlin Child Class

Kotlin Inheritance

Inheritance is the concept of creating class hierarchies wherein we override properties and functions of the base class in its subclasses as per our needs. All classes in Kotlin have a common superclass : Any.

Inheritance allows code reusability. Typically the superclass is known as the base class or the parent class and the subclasses are the derived/child class. Kotlin doesn’t allow a class to inherit from multiple classes because of famous diamond problem.

Here, we have a base class and a derived class. We create an object while instantiating the derived class then it is used to invoke the base class and derived class functions. The derived.A() is used to call the function A() which prints “Base Class” . The derived.B() is used to call the function B() which prints the variable name inherit from the base class and also prints “Derived class”.

  1. We can’t create an object for abstract class.
  2. All the variables (properties) and member functions of an abstract class are by default non-abstract. So, if we want to override these members in the child class then we need to use open keyword.
  3. If we declare a member function as abstract then we does not need to annotatate with open keyword because these are open by default.
  4. An abstract member function doesn’t have a body, and it must be implemented in the derived class.

Use of Inheritance –
Suppose there are three types of Employee in a company a webDeveloper , an iOSDeveloper and an androidDeveloper. All of them have some shared features like name, age and also have some special kind of skills.

First, we create three class individually and all employees have some common and specific skills.

Leave a Reply

Your email address will not be published. Required fields are marked *