Kotlin Inheritance and Polymorphism
In this tutorial, we will be discussing two important concepts of Object-Oriented Programming (OOP) in Kotlin - inheritance and polymorphism. These are fundamental pillars of OOP you should understand to master Kotlin or any object-oriented language.
What is Inheritance?
Inheritance is one of the four main concepts behind object-oriented programming (The other three are encapsulation, polymorphism, and abstraction). Inheritance allows one class to inherit the features (fields and methods) of another class. The class that inherits the features of another is known as the subclass (or derived class), and the class whose properties are inherited is known as the superclass (or parent class).
In Kotlin, all classes inherit from the Any
class by default. This means that the Any
class is a superclass for all classes.
Here is an example of inheritance in Kotlin:
open class Animal { // Superclass
open fun eat() {
println("The animal is eating")
}
}
class Cat : Animal() { // Subclass
override fun eat() {
println("The cat is eating")
}
}
In the above example, Cat
is a subclass of Animal
and inherits the eat()
method from Animal
. The open
keyword is used to allow a class or a function to be inheritable. The override
keyword is used to override the superclass method in the subclass.
What is Polymorphism?
Polymorphism is another one of the four main concepts behind object-oriented programming. The term polymorphism means 'having multiple forms'. In Kotlin, polymorphism allows a subclass to inherit the features of a superclass, and then modify those features to create more specialized forms.
Here is an example of polymorphism in Kotlin:
open class Animal { // Superclass
open fun eat() {
println("The animal is eating")
}
}
class Cat : Animal() { // Subclass
override fun eat() {
println("The cat is eating")
}
}
fun main() {
val myAnimal = Animal()
val myCat = Cat()
myAnimal.eat() // Outputs: The animal is eating
myCat.eat() // Outputs: The cat is eating
}
In the above example, Cat
is a subclass of Animal
and it overrides the eat()
method of Animal
. So, when we call the eat()
method on the myCat
object, it runs the eat()
method in the Cat
class, not the one in the Animal
class. This is polymorphism.
Conclusion
By understanding inheritance and polymorphism, you're now familiar with two of the main concepts behind OOP in Kotlin. These are fundamental to writing efficient, modular, and reusable code. In the next tutorials, we will discuss the remaining two OOP concepts - encapsulation and abstraction.