Abstract Classes in Kotlin

Abstract classes are classes that cannot be instantiated directly and are meant to be subclassed. They can contain both abstract members (without implementation) and concrete members (with implementation). Abstract classes are used to define a common blueprint for multiple subclasses.

1. Why Abstract Classes Matter

2. What is an Abstract Class?

An abstract class is declared using the abstract keyword. Abstract members are declared without implementation, and concrete members can have full implementations.


abstract class Aircraft(val name: String) {
    abstract fun fly()                // Must be implemented by subclasses
    open fun startEngine() {          // Optional override
        println("$name engine started")
    }
}
  

3. Implementing Abstract Classes

Subclasses must implement all abstract members:


class Jet(name: String) : Aircraft(name) {
    override fun fly() {
        println("$name is flying at supersonic speed")
    }

    override fun startEngine() {
        super.startEngine()  // Optionally call parent implementation
        println("Jet-specific engine checks")
    }
}

fun main() {
    val jet = Jet("F-16")
    jet.startEngine()
    jet.fly()
}
  

Output:


F-16 engine started
Jet-specific engine checks
F-16 is flying at supersonic speed
  

4. Key Points About Abstract Classes

5. Abstract vs Interface

6. Technical Interview Questions

7. Key Takeaways