override
- Kotlin course
- Intermediate
- Lesson 8/116
- 5 min
Learn to redefine methods with override.
override
To redefine an open method of the base class in a subclass, you use the override modifier. This is the standard way to add subclass-specific behavior.
Example: class Circle : Shape() { override fun area(): Double { return 3.14 * r * r } }. If area is marked open in Shape, the subclass overrides it with override. Forgetting override is a compile error; Kotlin avoids accidental method hiding. Overridden methods are themselves open by default.
The open + override rule
To redefine a method in a subclass with override, the same method must be open in the base class. If it is not open, override fails to compile.
Example: open class Shape { open fun area() = 0.0 }; the subclass can write override fun area() = .... If area is not open in Shape, the subclass override is a compile error. Writing final override blocks further overriding down the hierarchy.
Practice The Shape base class and the Circle subclass
Define an open class named Shape with a primary constructor taking val name: String. Add an open fun area(): Double = 0.0 method. Define a subclass named Circle with a primary constructor taking name: String, val radius: Double that inherits from Shape(name). Its override fun area(): Double returns 3.14 * radius * radius. In main create a Circle("Disk", 2.0) instance and print area().
Starter code
// Shape base class (open)
// area method, default zero
// Circle subclass, name and radius
// override to compute area
// instantiate Circle in main, print areaSample solution
open class Shape(val name: String) {
open fun area(): Double = 0.0
}
class Circle(name: String, val radius: Double) : Shape(name) {
override fun area(): Double {
return 3.14 * radius * radius
}
}
fun main() {
val c = Circle("Disk", 2.0)
println(c.area())
}Expected output
12.56
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Match the override pattern
| Term | Meaning |
|---|---|
open fun area() |
Method opened in base |
override fun area() |
Redefinition in subclass |
: Shape() |
Inheritance and constructor |
return 3.14 * r * r |
New body |
2 A subclass writes <code>override fun area()</code> but <code>area</code> is not <code>open</code> in the base. What happens?
- A compile error is raised Correct answer
- The code compiles normally
- The method is hidden at runtime
- The base body runs instead
Explanation: A non-open method cannot be overridden; the compiler rejects it.
3 Complete the override method
class Circle : Shape() {
____ fun area(): Double {
return 3.14 * r * r
}
}
class Circle : Shape() {
override fun area(): Double {
return 3.14 * r * r
}
}
Explanation: override redefines the open method of the base class.