Inheritance
We'll cover the following
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 further overriding that method.
You may override a property, either defined within a class or within the parameter list of a constructor. A val
property in the base may be overridden with a val
or var
in the derived. But a var
property in the base may be overridden only using var
in the derived. The reason for this restriction is that val
only has a getter and you may add a setter in the derived by overriding with var
. But you shouldn’t attempt to withdraw the setter that’s for a base’s var
by overriding with a val
in the derived.
Creating a base class
All these concepts will take shape in the next example. The Vehicle
class that follows is marked as open
and so can serve as a base class.
Get hands-on with 1200+ tech skills courses.