Ad space (banner)
๐ŸŽฏKotlin Lessons
Lesson 16 / 68

Inheritance (Extending a Class)

In this lesson you will learn how to extend a class through inheritance in Kotlin, so classes that share characteristics can reuse code. This is for anyone searching for "Kotlin inheritance how to use".

You inherit with : ParentClassName. Marking the parent class and its methods open is what allows a child class to override them. Gathering the shared parts into a parent class saves you writing the same code repeatedly.

The sample code makes open class Animal the parent, has class Dog(name: String) : Animal(name) inherit from it, and replaces the parent's method with override fun speak(). The key point is that you keep the parent's functionality and change only the parts you need.

A common stumbling block for beginners is forgetting the open keyword. Kotlin classes are final by default and cannot be inherited, so allowing inheritance requires stating open explicitly.

In real-world development this design, which prevents unintended inheritance, makes for safer class design.

๐Ÿ“– Reference code
โœ๏ธ Your code
Type your code, then press "Run"

๐Ÿงช This site can't compile or run Kotlin directly, so it checks on the spot whether what you typed matches the reference code (scoring happens entirely in your browser โ€” nothing is sent anywhere).

Ad space (banner)
Ad space (in-article)