Inheritance
In Java and C#, a class can be subclassed and a method overridden unless you explicitly mark them final or sealed. Kotlin flips that default: every class and every function is final unless you mark it open. This is a deliberate design choice — it means a class's author has to actively decide to support being extended, rather than it happening by accident.
open class Animal(val name: String) {
open fun speak(): String {
return "$name makes a sound"
}
}
class Cat(name: String) : Animal(name) {
override fun speak(): String {
return "$name meows"
}
}
fun main() {
val cat = Cat("Whiskers")
println(cat.speak())
}Whiskers meows
What the real compiler error looks like
Leaving out open on both the class and the method isn't a warning — it's a compile error. This is genuinely what the compiler reports — captured from a real run, not written to look plausible:
class Animal {
fun speak(): String {
return "..."
}
}
class Dog : Animal() {
override fun speak(): String {
return "Woof"
}
}
fun main() {
println(Dog().speak())
}OpenJDK 64-Bit Server VM warning: Options -Xverify:none and -noverify were deprecated in JDK 13 and will likely be removed in a future release.
Main.kt:7:13: error: this type is final, so it cannot be inherited from
class Dog : Animal() {
^
Main.kt:8:5: error: 'speak' in 'Animal' is final and cannot be overridden
override fun speak(): String {
^Next: interfaces — describing shared behavior across unrelated classes.
Practice exercise
Define an open class Animal with an open fun speak() returning "$name makes a sound". Define a class Cat that extends Animal and overrides speak() to return "$name meows". Create a Cat named "Whiskers" and print its speak().