Kotlin Inheritance
Inheritance is a way for one class to build on another class. The child class gains the properties and methods of the parent class.
A child class gains a parent method
Dog names Animal as its parent. Dog defines no speak method, and the call still works.
open class Animal(val name: String) {
open fun speak() {
println("$name makes a sound")
}
}
class Dog(name: String) : Animal(name)
fun main() {
val dog = Dog("Rex")
dog.speak()
}A child class replaces a parent method
Dog marks speak with override. The call now runs the Dog version of speak.
open class Animal(val name: String) {
open fun speak() {
println("$name makes a sound")
}
}
class Dog(name: String) : Animal(name) {
override fun speak() {
println("$name barks")
}
}
fun main() {
val dog = Dog("Rex")
dog.speak()
}Each child answers in its own way
The list holds a Dog and a Cat as Animal values. One call to speak gives two different answers, and that is polymorphism.
open class Animal(val name: String) {
open fun speak() {
println("$name makes a sound")
}
}
class Dog(name: String) : Animal(name) {
override fun speak() {
println("$name barks")
}
}
class Cat(name: String) : Animal(name) {
override fun speak() {
println("$name meows")
}
}
fun main() {
val animals = listOf<Animal>(Dog("Rex"), Cat("Mia"))
for (animal in animals) {
animal.speak()
}
}Example
open class Animal(val name: String) {
open fun speak() {
println("$name makes a sound")
}
}
class Dog(name: String) : Animal(name) {
override fun speak() {
println("$name barks")
}
}
class Cat(name: String) : Animal(name) {
override fun speak() {
println("$name meows")
}
}
fun main() {
val animals = listOf<Animal>(Animal("Solo"), Dog("Rex"), Cat("Mia"))
for (animal in animals) {
animal.speak()
}
}Key points
- Inheritance: one class builds on another class
- Parent class: the class that other classes build on
- Child class: a class that builds on a parent class
- Use open before class to allow child classes to build on it
- Use a colon after the child class name to name its parent class
- Use override to replace a parent method in a child class
In this example, the list holds three Animal values. The plain Animal prints its own sound first. The Dog and Cat values answer the same speak call with their override versions.
Note
A class that is not marked open cannot be used as a parent class.
Try it Yourself
Edit the code, then press Run.
Running is simulated ยท Kotlin Playground
Exercise
What must a class be marked as before another class can build on it?