super
- Kotlin course
- Intermediate
- Lesson 9/116
- 5 min
Learn to call base class methods with super.
super
To call a method of the base class from a subclass, you use the super keyword. This is commonly used when an overridden method should also run the base behavior.
Example: override fun start() { super.start(); println("ready") }. Here super.start() calls the base start, then the extra behavior runs. This pattern is common to keep the base work and add something on top. Calling start() directly instead of super.start() would recurse infinitely.
super and init
The primary constructor of a subclass calls the base constructor with : Base(...). This call also runs the init blocks of the base class. The super keyword instead accesses base methods inside method bodies.
Example: class Car(brand: String) : Vehicle(brand) { override fun start() { super.start() } }. Here Vehicle(brand) calls the base constructor and runs Vehicle's init blocks. super.start() calls the base start method from within a body. The two uses are distinct.
Practice The Vehicle base class and the Car subclass
Define an open class named Vehicle with a primary constructor taking val brand: String. Add an open fun start() method whose body writes println("$brand started"). Define a subclass named Car with a primary constructor taking brand: String, val model: String that inherits from Vehicle(brand). Its override fun start() first calls super.start(), then writes println("$model ready"). In main create a Car("Toyota", "Corolla") instance and call start.
Starter code
// Vehicle base class (open)
// open fun start: write brand started
// Car subclass, brand and model
// override fun start: super first, then model ready
// instantiate Car in main, call startSample solution
open class Vehicle(val brand: String) {
open fun start() {
println("$brand started")
}
}
class Car(brand: String, val model: String) : Vehicle(brand) {
override fun start() {
super.start()
println("$model ready")
}
}
fun main() {
val c = Car("Toyota", "Corolla")
c.start()
}Expected output
Toyota started Corolla ready
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 What does the pattern <code>override fun start() { super.start() }</code> do?
- It runs only the subclass start
- It calls the base start first, then runs the rest of the subclass body Correct answer
- It hides the base start
- It creates infinite recursion
Explanation: super.start() runs the base first; then the rest of the subclass body runs.
2 Complete the super call
override fun start() {
____.start()
println("ready")
}
override fun start() {
super.start()
println("ready")
}
Explanation: super.start() calls the method of the base class.
3 Match the super usages
| Term | Meaning |
|---|---|
: Vehicle(brand) |
Base constructor call |
super.start() |
Base method call |
override fun start() |
Redefinition |
init { ... } |
Initialization block |