nadirbasalamah
Posted on October 13, 2021
Inheritance is a mechanism to create a sub class that inherits attributes and methods from parent class. Basically, each class that created in Kotlin is inherits attributes and methods from Any
class.
In general, parent class is a general representation from an entity whilst sub class is a more specific representation from an entity. The inheritance mechanism is illustrated in this picture.
Create an Inheritance
In Kotlin, the inheritance mechanism can be created with :
notation followed with the parent class name. In this example, there are two classes called Car
and RaceCar
. The Car
class is a parent class when the RaceCar
class is a sub class from Car
class. The relation between Car
class and RaceCar
class is illustrated in this picture.
The Car
class is created inside Car.kt
file.
open class Car (val manufacturer: String, val type: String) {
open fun run() {
println("Running...")
}
}
The RaceCar
class is created inside RaceCar.kt
file.
// create a RaceCar class that inherits Car class
class RaceCar(val team: String, manufacturer: String, type: String) : Car(manufacturer, type) {
// create a specific implementation for run() method
// in RaceCar class
override fun run() {
println("Running with racing spec from $team")
}
}
The object from RaceCar
class is created in main()
method.
fun main() {
// create an object from RaceCar class
val raceCar = RaceCar("Manthey Racing","Porsche","911 GT3")
// call run() method
raceCar.run()
}
Output
Running with racing spec from Manthey Racing
Based on the code above, the Car
class is acts as parent class with open
keyword is added before class declaration. The open
keyword means a class can be inherited by another class. In Car
class, the run()
method is added with open
keyword that means this method can be override or implemented specifically in a sub class.
The sub class from Car
class is RaceCar
class. The RaceCar
class implements the run()
method specifically with override
keyword. The object from RaceCar
class is created in main()
method then the run()
method is called from the created object.
Notes
The multiple inheritance mechanism is not available in Kotlin. Multiple inheritance is a mechanism that allows a class could inherits from many parent classes. This is the illustration of multiple inheritance.
The multilevel inheritance is available in Kotlin. This is the illustration of multilevel inheritance.
Sources
- Learn more about inheritance in Kotlin in this link.
I hope this article is helpful for learning the Kotlin programming language. If you have any thoughts or comments you can write in the discussion section below.
Posted on October 13, 2021
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.