Introduction to Inheritance

Discover the concept of inheritance in Kotlin, where classes inherit properties and methods, and learn how to customize inherited behavior.

Ancient philosophers observed that many classes of objects share the same characteristics. For instance, all mammals have hair or fur, are warm-blooded, and feed their young with milk. In programming, we represent such relationships using inheritance.

Superclasses and subclasses

When a class inherits from another class, it has all its member functions and properties. The class that inherits is known as a subclass of the class it inherits from, which is called a superclass. They are also known as child and parent classes.

Inheriting from classes

In Kotlin, all classes are closed by default, which means we cannot inherit from them. We need to open a class using the open keyword to allow inheritance from it. To inherit from a class, we place a colon (:) after the primary constructor (or after the class name if there is no primary constructor), and then we invoke the superclass constructor.

Example

In the example below, the class Dog inherits from the class Mammal. Since Mammal has no constructor specified, we call it without arguments, i.e., with Mammal(). This way, Dog inherits all the properties and methods from Mammal.

Get hands-on with 1200+ tech skills courses.