0
0
KotlinHow-ToBeginner · 3 min read

How to Use Abstract Class in Kotlin: Syntax and Examples

In Kotlin, an abstract class is a class that cannot be instantiated directly and can contain abstract methods without implementation. You use the abstract keyword before the class and its methods, and subclasses must override these abstract methods to provide implementations.
📐

Syntax

An abstract class is declared with the abstract keyword before the class keyword. It can have abstract methods (without body) and concrete methods (with body). Subclasses must override all abstract methods.

  • abstract class ClassName: Declares an abstract class.
  • abstract fun methodName(): Declares an abstract method without implementation.
  • fun methodName(): Declares a concrete method with implementation.
kotlin
abstract class Animal {
    abstract fun sound(): String
    fun sleep() {
        println("Sleeping...")
    }
}
💻

Example

This example shows an abstract class Animal with an abstract method sound(). The subclass Dog overrides sound() and provides its own implementation. The program creates a Dog object and calls both methods.

kotlin
abstract class Animal {
    abstract fun sound(): String
    fun sleep() {
        println("Sleeping...")
    }
}

class Dog : Animal() {
    override fun sound(): String {
        return "Bark"
    }
}

fun main() {
    val dog = Dog()
    println(dog.sound())
    dog.sleep()
}
Output
Bark Sleeping...
⚠️

Common Pitfalls

Common mistakes when using abstract classes in Kotlin include:

  • Trying to create an instance of an abstract class directly, which is not allowed.
  • Not overriding all abstract methods in the subclass, causing a compilation error.
  • Forgetting to mark overridden methods with override keyword.
kotlin
/* Wrong: Cannot instantiate abstract class */
// val animal = Animal() // Error

/* Wrong: Missing override of abstract method */
// class Cat : Animal() { }

/* Right: Override abstract method */
class Cat : Animal() {
    override fun sound(): String {
        return "Meow"
    }
}

Key Takeaways

Use the abstract keyword to declare abstract classes and methods in Kotlin.
Abstract classes cannot be instantiated directly; create subclasses that override abstract methods.
Always use the override keyword when implementing abstract methods in subclasses.
Abstract classes can have both abstract and concrete methods.
Trying to instantiate an abstract class or missing method overrides causes compile errors.