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”.
- We can’t create an object for abstract class.
- 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.
- If we declare a member function as abstract then we does not need to annotatate with open keyword because these are open by default.
- 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.