Inheritance is one of the most powerful features of Object-Oriented Programming. It allows you to create a new class based on an existing class.
The concept is divided into two categories:
To inherit from a class, you use the colon (:) operator.
open KeywordIn many programming languages (like Java), classes are inheritable by default. In Kotlin, classes are final by default, meaning they cannot be inherited!
To allow a class to be inherited, you must explicitly mark it with the open keyword.
// This class can now be inherited!
open class ParentClass {
// Code
}
Let's look at a practical example. We will create an open superclass called Vehicle, and a subclass called Car that inherits from it.
The Car class will automatically gain all the properties and functions of the Vehicle class, saving us from writing duplicate code!
// 1. Create the Superclass (must be 'open')
open class Vehicle {
var brand = "Ford"
fun honk() {
println("Beep beep!")
}
}
// 2. Create the Subclass using a colon ( : )
// Notice we must put () after Vehicle to call its constructor
class Car : Vehicle() {
var modelName = "Mustang"
}
fun main() {
// Create an object of the subclass
val myCar = Car()
// Access property from the Subclass
println(myCar.modelName)
// Access property and function inherited from the Superclass!
println(myCar.brand)
myCar.honk()
}
Why use Inheritance? It is crucial for code reusability (the DRY principle). You define general behavior once in the parent, and specific details in the children.
Sometimes, the subclass inherits a function from the superclass but wants to modify its behavior. This is called overriding.
To override a function, two things must happen:
open.override.
open class Animal {
// Must be open to be overridden
open fun makeSound() {
println("The animal makes a sound")
}
}
class Dog : Animal() {
// Override the inherited function
override fun makeSound() {
println("The dog barks: Woof woof!")
}
}
class Cat : Animal() {
override fun makeSound() {
println("The cat meows: Meow!")
}
}
fun main() {
val animal = Animal()
val dog = Dog()
val cat = Cat()
animal.makeSound()
dog.makeSound()
cat.makeSound()
}
super KeywordWhat if you want to override a function, but you still want to use the original code from the parent class? You can call the parent's version of the function using the super keyword.
open class Employee {
open fun doWork() {
println("Employee is working...")
}
}
class Manager : Employee() {
override fun doWork() {
// Call the parent function first
super.doWork()
// Then add specific Manager behavior
println("Manager is assigning tasks.")
}
}
fun main() {
val m = Manager()
m.doWork()
}
In the example above, calling m.doWork() runs the code from Employee, and immediately follows it up with the code from Manager!
Which keyword is required to allow a Kotlin class to be inherited?