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 property
1open class Animal(val name: String) {
// open lets subclasses override this default implementation
2 open fun speak() = "..."
3}
4
// name here is a plain constructor parameter, passed on to Animal's constructor
5class Dog(name: String) : Animal(name) {
// override replaces speak() for Dog
6 override fun speak() = "Woof!"
7}
8
// Cat is another subclass with its own sound
9class Cat(name: String) : Animal(name) {
10 override fun speak() = "Meow!"
11}
12
// Both objects are stored as the common type Animal
13val 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

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

More Kotlin examples at level 5

← Kotlin typing practice