Overriding Members
Part of the Object Oriented Programming section of Coddy's Kotlin journey. Lesson 18 of 57.
A subclass can replace an inherited method with its own version. The superclass marks the method open, and the subclass declares it again with override:
open class Animal(val name: String) {
open fun sound() = "..."
}
class Dog(name: String) : Animal(name) {
override fun sound() = "Woof"
}
class Cat(name: String) : Animal(name) {
override fun sound() = "Meow"
}Inside main:
println(Dog("Rex").sound())
println(Cat("Tom").sound())
println(Animal("Generic").sound())Output:
Woof
Meow
...The version that runs is chosen by the object's actual class, even when the variable's type is the superclass. Code inside the superclass that calls an open method gets the subclass's version too:
open class Animal(val name: String) {
open fun sound() = "..."
fun speak() = "$name says ${sound()}"
}
class Dog(name: String) : Animal(name) {
override fun sound() = "Woof"
}Inside main:
val pets: List<Animal> = listOf(Dog("Rex"), Animal("Generic"))
for (p in pets) println(p.speak())Output:
Rex says Woof
Generic says ...Properties can be overridden the same way: open val in the superclass, override val in the subclass, either as a normal property, a constructor property or a computed getter:
open class Shape {
open val name = "shape"
open val corners = 0
}
class Triangle : Shape() {
override val name = "triangle"
override val corners = 3
}
class Polygon(override val corners: Int) : Shape() {
override val name: String
get() = "$corners-gon"
}Inside main:
for (s in listOf(Shape(), Triangle(), Polygon(6))) println("${s.name}: ${s.corners}")Output:
shape: 0
triangle: 3
6-gon: 6A member marked override is open again, so a subclass of the subclass may override it once more; final override stops that. A member without open cannot be overridden at all, and a subclass may not declare a member with the same signature:
open class Animal {
open fun sound() = "..."
fun sleep() = "zzz"
}
open class Dog : Animal() {
final override fun sound() = "Woof"
}
class Puppy : Dog() {
// override fun sound() = "Yip" // error: 'sound' in 'Dog' is final
// fun sleep() = "nap" // error: 'sleep' hides a member of the superclass
}Challenge
EasyAnimal has legs() (4), sound() (...) and describe(), which returns Rex has 4 legs and says Woof, built from legs() and sound(). Make legs() and sound() overridable and complete the subclasses by overriding only those two methods: Dog says Woof, Bird has 2 legs and says Tweet, and Snake has 0 legs and says Hiss. describe() stays as it is in Animal.
The supplied code reads lines dog,Rex, bird,Pip, snake,Kaa or any other kind (a plain Animal), stores the animals in one List<Animal> and prints describe() for each.
Your code goes in Animal.kt, Dog.kt, Bird.kt and Snake.kt. Main.kt holds the supplied input/output code and cannot be edited.
Try it yourself
fun main() {
// Supplied input/output code: keep it as it is
val input = generateSequence(::readLine).toList()
val animals = mutableListOf<Animal>()
for (line in input) {
val (kind, name) = line.split(",")
animals.add(when (kind) {
"dog" -> Dog(name)
"bird" -> Bird(name)
"snake" -> Snake(name)
else -> Animal(name)
})
}
for (a in animals) println(a.describe())
}
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Object Oriented Programming
1Classes and Objects
Working With FilesDefining ClassesPrimary Constructorsinit Blocks and ValidationSecondary ConstructorsRecap - Library Card4Inheritance
Open Classes and SubclassesOverriding Memberssuper and ConstructorsAbstract ClassesRecap - Staff Directory2Properties and Encapsulation
Custom AccessorsVisibility ModifiersPrivate Setterslazy and lateinitRecap - Bank Account5Interfaces
Declaring InterfacesDefault MethodsMultiple InterfacesInterfaces as TypesRecap - Payment Methods8Generics
Generic FunctionsGeneric ClassesType ConstraintsVariance With in and outRecap - Priority Queue11Project: Library Management
Books and MembersBorrowing BooksPractice on your own: Kotlin playground