Inheritance

When you use inheritance, you’ll feel the extra layer of safety and protection that Kotlin provides. Since inheritance is one of the misused concepts in OO programming, Kotlin helps you make sure that your intentions are laid out very explicitly to the users of your classes.

Inheritance in Kotlin

Kotlin doesn’t want classes to accidentally serve as a base class. As an author of a class, you have to provide explicit permission for your class to be used as a base class. Likewise, when writing a method, you have to tell Kotlin that it’s OK for a derived class to override that method. Let’s take a look at how Kotlin provides this safety net.

Unlike interfaces, classes in Kotlin are final by default—that is, you can’t inherit from them. Only classes marked open may be inherited from. Only open methods of an open class may be overridden in a derived class and have to be marked with override in the derived. A method that isn’t marked open or override can’t be overridden. An overriding method may be marked final override to prevent a subclass from ...