Inheritance lets one class (the child or subclass) reuse and extend another class (the parent or superclass). For example, Car and Bike can both inherit from Vehicle.
Page Contents
Classes are final by default
In Kotlin, a class can’t be inherited from unless you mark it open. This prevents accidental changes to classes that weren’t designed for it.
open class Vehicle(val brand: String) {
fun start() = println("$brand is starting")
}
class Car(brand: String, val doors: Int) : Vehicle(brand)
fun main() {
val car = Car("Tata", 4)
car.start() // inherited from Vehicle
println("${car.brand} has ${car.doors} doors")
}Output:
Tata is starting Tata has 4 doors
class Car(...) : Vehicle(brand) means “Car inherits from Vehicle, and passes brand to Vehicle‘s constructor”.
Overriding functions: open and override
A function can only be overridden if it’s open in the parent. The child must write override:
open class Animal(val name: String) {
open fun sound() = "..."
fun describe() = "$name says ${sound()}"
}
class Dog(name: String) : Animal(name) {
override fun sound() = "Woof"
}
class Cat(name: String) : Animal(name) {
override fun sound() = "Meow"
}
fun main() {
println(Dog("Bruno").describe())
println(Cat("Kitty").describe())
}Output:
Bruno says Woof Kitty says Meow
Calling the parent with super
open class Notification(val text: String) {
open fun show() = println("Notification: $text")
}
class UrgentNotification(text: String) : Notification(text) {
override fun show() {
println("⚠ URGENT")
super.show() // run the parent's version too
}
}
fun main() {
UrgentNotification("Server is down").show()
}Output:
⚠ URGENT Notification: Server is down
Overriding properties
open class Shape {
open val name = "Shape"
open val sides = 0
}
class Triangle : Shape() {
override val name = "Triangle"
override val sides = 3
}
fun main() {
val t = Triangle()
println("${t.name} has ${t.sides} sides")
}Output:
Triangle has 3 sides
Polymorphism: one type, many forms
A variable of the parent type can hold any child object. The correct overridden function runs automatically:
open class Employee(val name: String, val baseSalary: Int) {
open fun monthlyPay() = baseSalary
}
class Manager(name: String, baseSalary: Int, val bonus: Int) : Employee(name, baseSalary) {
override fun monthlyPay() = baseSalary + bonus
}
class Intern(name: String) : Employee(name, 15000) {
override fun monthlyPay() = baseSalary / 2 + 5000
}
fun main() {
val team: List<Employee> = listOf(
Employee("Asha", 60000),
Manager("Ravi", 90000, 20000),
Intern("Zoya")
)
for (e in team) println("${e.name}: ₹${e.monthlyPay()}")
println("Total: ₹${team.sumOf { it.monthlyPay() }}")
}Output:
Asha: ₹60000 Ravi: ₹110000 Zoya: ₹12500 Total: ₹182500
Stopping further overriding: final override
An override is itself open by default. Add final to stop grandchildren from overriding it:
open class Base { open fun greet() = "Hi" }
open class Middle : Base() { final override fun greet() = "Hello" }
// class Last : Middle() { override fun greet() = "Hey" } // ❌ greet is finalChecking the type
open class Vehicle
class Car : Vehicle()
class Bike : Vehicle()
fun main() {
val vehicles = listOf(Car(), Bike(), Car())
println(vehicles.count { it is Car })
println(vehicles.filterIsInstance<Bike>().size)
}Output:
2 1
Inheritance vs composition
Inheritance models an “is a” relationship: a Car is a Vehicle. If the relationship is “has a” (a Car has an Engine), give the class a property instead:
class Engine(val horsepower: Int) class Car(val engine: Engine) // composition, not inheritance
Prefer composition when in doubt. Deep inheritance chains are hard to change.
Common mistakes
- Forgetting
open:class Vehiclecan’t be inherited from, andfun start()can’t be overridden. - Forgetting
()after the parent: write: Vehicle()(or pass its arguments), not: Vehicle. - Calling open functions from a constructor: the child’s override runs before the child’s properties are set, which can give
nullor 0.
Exercise
Create a Shape hierarchy where Circle and Square override an area() function, then print the total area of a list of shapes.
import kotlin.math.PI
open class Shape(val name: String) {
open fun area(): Double = 0.0
}
class Circle(val radius: Double) : Shape("Circle") {
override fun area() = PI * radius * radius
}
class Square(val side: Double) : Shape("Square") {
override fun area() = side * side
}
fun main() {
val shapes = listOf(Circle(1.0), Square(3.0), Circle(2.5))
for (s in shapes) println("${s.name}: ${"%.2f".format(s.area())}")
println("Total: ${"%.2f".format(shapes.sumOf { it.area() })}")
}Output:
Circle: 3.14 Square: 9.00 Circle: 19.63 Total: 31.78
In the next lessons you’ll see a better way to write Shape: as an abstract class or an interface, so every shape is forced to provide its own area().
FAQ
Why are Kotlin classes final by default?
To prevent fragile designs. A class has to be deliberately made open before others can inherit from it.
What is the difference between open and override?
open in the parent allows overriding. override in the child actually replaces the member.
Can a Kotlin class inherit from multiple classes?
No, only one class. It can implement many interfaces, though.
