Inheritance

Inheritance is one of the main aspects of object-oriented programming. Basically, it allows classes (subclasses) to inherit members from base types (superclasses). They usually have their own functions and properties, which are not found in the base type. With inheritance, you can achieve code reuse, build class hierarchies, or extend base types with additional functionality.

Let's take a look at an example. We have the old User class we used in this chapter, and let's say we also need to have a class that represents administrator users, which will have the same properties as the base User class plus one additional property, role. We can say this would be a good use of inheritance, so let's create the AdminUser class, which extends the base User class:

open class User(var firstName: String,
var lastName: String,
var birthYear: String)

class AdminUser(firstName: String,
lastName: String,
birthYear: String,
var role: String): User(firstName, lastName, birthYear)

You can see that we marked the base User class with the open keyword. This is needed because classes in Kotlin are final (not inheritable) by default.

The actual inheritance syntax is expressed with a colon after the class declaration. After the colon comes the type we wish to inherit from.

Another thing you can see in the syntax is that we called the base type constructor and passed the three required parameters. When inheriting from a class that has a primary constructor, you always have to call it in that place.

If a base class has only secondary constructors, then you can call them from the inheriting class with the super keyword:

open class User {

constructor(firstName: String,
lastName: String,
birthYear: String)
}

class AdminUser : User {
constructor(firstName: String,
lastName: String,
birthYear: String,
role: String) : super(firstName, lastName, birthYear)
}

The constructor parameters needed for the base type are also present in the inherited class, but note that they are not properties there (they don't have the var or val keywords).

Kotlin wouldn't allow this, since it would mean that we are then overriding the base type's properties. Kotlin, the same as Java, doesn't support multiple inheritance, that is, you can inherit only from one class.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.145.191.134