Implement Inheritance in Kotlin Class with Examples

Inheritance is a fundamental object-oriented programming language concept that allows us to inherit properties and functions from another class. In Kotlin, we can only integrate a single inheritance, which means a class can only inherit one superclass. In today’s tutorial, we learn how to implement inheritance in Kotlin class with basic code syntax, superclass, and subclass examples.

Implement Inheritance in Kotlin Class with Examples

Implement Inheritance in Kotlin Class with Examples

What is Inheritance?

In inheritance, a class can inherit functions and properties from another class. There are two classes: the Superclass(Base class) and the Derived class(Subclass).

  1. Super class(Base class): The class whose functions and properties are inherited into another class is called a Superclass. To make a class accessible for inherited you have to add an open keyword at the time of class declaration.
  2. Derived class(Subclass): The class that inherits other class functions and properties within is called a Subclass.

Basic Inheritance Syntax in Kotlin:

In our example, we are inheriting variables and functions into a subclass. Please make sure to add the open keyword to allow inheriting.

Simple Inheritance Example in Kotlin:

Code explanation:

In our basic inheritance example, we are overriding only 1 variable and 1 function and calling the other 2 functions directly.

Implement Inheritance in Kotlin with properties and methods:

Code explanation:

We have created a Superclass named CommonSchool with 2 parameters. These parameters are used in member functions of the class. Now we are inheriting this class into School class. We are getting both our superclass parameters in the subclass as parameters and passing them again. In the end, we are creating an instance(object) of our Subclass and calling the superclass functions.

Comments

No comments yet. Why don’t you start the discussion?

Leave a Reply

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