Class Inheritance in Kotlin


Class Inheritance in Kotlin

One of the most important features of object-oriented programming is Inheritance. It enables the reuse of inheritance code, allowing all features from an existing class (base class) to be inherited by a new class (origin class). Additionally, it can add some elements of its own to the driven class. The open keyword in front of the base class allows the class to inherit from the base.

Inheriting property and methods from the base class

When we inherit a class, we inherit all the benefits and functions. Using the derived class object, we can use essential class variables and procedures in the derived class and call functions.

Why is inheritance helpful and its use?

Inheritance programmers can create classes built into existing classes, use the same behavior (interface recognition), reuse code, and specify a new implementation to extend the original software through public classes and interfaces freely.

Inheritance Primary Constructor - If the derived class contains a primary constructor, we need to start the base class constructor with the parameters of the driven class.

Inheritance Secondary Constructor - If the resulting class does not contain a primary constructor, we must call the introductory class secondary constructor from the derived class secondary constructor with the super keyword. We need to start the base class secondary constructor with the parameters of the derived class.

To Override member functions and properties - If the base class and the derived class contain the same member function with the same name, we can override the base member function in the derived class and mark the base class member function with the open keyword.

To call the Superclass implementation - We can call essential class member functions or properties from the derived class with the super keyword. The program below calls the primary class property color and the function display company () in the derived type using the super keyword.