Class inheritance in Kotlin
Level 5333 keystrokes
Kotlin classes and methods are final by default, so Animal and speak() are marked open to allow inheritance and overriding. Looping over a List<Animal> calls each object's own speak() (polymorphism).
Kotlin code
// open allows subclassing (classes are final by default); name is a property1open class Animal(val name: String) { // open lets subclasses override this default implementation2 open fun speak() = "..."3}4 // name here is a plain constructor parameter, passed on to Animal's constructor5class Dog(name: String) : Animal(name) { // override replaces speak() for Dog6 override fun speak() = "Woof!"7}8 // Cat is another subclass with its own sound9class Cat(name: String) : Animal(name) {10 override fun speak() = "Meow!"11}12 // Both objects are stored as the common type Animal13val pets: List<Animal> = listOf(Dog("Rex"), Cat("Whiskers"))// Each actual class's speak() runs: prints Rex: Woof! and Whiskers: Meow!14for (pet in pets) println("${pet.name}: ${pet.speak()}")Output
Rex: Woof! Whiskers: Meow!
Practice typing this code. Results are not recorded in the rankings.
Symbols in this code
The symbols you type in this Kotlin code and how often they appear.
(× 14)× 14"× 12:× 7.× 5{× 5}× 5=× 4!× 2$× 2