Kotlin Tutorial · Object-Oriented Kotlin · Lesson 14 of 31
Kotlin Inheritance and Interfaces
Classes are final by default: use open, abstract classes and interfaces to share behaviour and types.
open and override
Classes and members are final by default. Mark a class open to allow subclasses and a member open to
allow overriding; the subclass writes override.
open class Notifier(val recipient: String) {
open fun send(message: String) = println("To $recipient: $message")
}
class SmsNotifier(phone: String) : Notifier(phone) {
override fun send(message: String) = super.send(message.take(20).trimEnd() + "...")
}
fun main() {
val notifiers = listOf(Notifier("[email protected]"), SmsNotifier("+351 900 000 000"))
for (n in notifiers) n.send("Your order has been shipped today")
}
Output
To [email protected]: Your order has been shipped today To +351 900 000 000: Your order has been...
Run this on your computer — see “Get Started” for setup.
Abstract classes and interfaces
An interface declares behaviour and can provide default implementations; a class can implement many. An abstract class can also hold state and constructor logic, but a class extends only one.
interface Shape {
val name: String
fun area(): Double
fun describe() = "$name with area ${"%.1f".format(area())}" // default implementation
}
abstract class Polygon(override val name: String, val sides: Int) : Shape
class Square(val side: Double) : Polygon("square", 4) {
override fun area() = side * side
}
class Circle(val radius: Double) : Shape {
override val name = "circle"
override fun area() = Math.PI * radius * radius
}
fun main() {
val shapes: List<Shape> = listOf(Square(3.0), Circle(1.0))
shapes.forEach { println(it.describe()) }
println(shapes.filterIsInstance<Polygon>().map { it.sides })
}
Output
square with area 9.0 circle with area 3.1 [4]
Run this on your computer — see “Get Started” for setup.
Test yourself
Why do you need open before a class in Kotlin?
To make it publicClasses are final by default, so open allows subclassingTo make it abstractTo allow it to be instantiated
Show answer
Answer: Classes are final by default, so open allows subclassing