Kotlin Abstract Classes

Abstract classes

The abstract modifier defines an abstract class. An abstract class can have abstract functions and abstract properties. It can contain abstract members, cannot be instantiated as-is, and must be inherited by a subclass that implements its abstract methods and properties. In other words, an abstract class defines the rules for the methods and properties a subclass must implement.

The Greeter abstract class below has an abstract property named name and an abstract method named greet. These abstract members only have signatures, so you can tell that they do not have implementations.

Example: Abstract class

abstract class Greeter {            // Abstract class
    abstract var name: String       // Abstract property
    abstract fun greet(): String    // Abstract function
}

A subclass that inherits from Greeter is defined below. Each abstract member is overridden with the override keyword. In Kotlin, the override keyword is required when overriding a member. Also, an abstract class can be inherited without open.

Example: Subclass that inherits an abstract class

class Hello : Greeter() {                    // Subclass that implements the abstract class
    override var name: String = "devkuma"    // Implements the abstract property
    override fun greet(): String = "Hello"   // Implements the abstract function
}

Now run the subclass that inherits the abstract class.

Example: Running the class

fun main() {
    var hello = Hello()
    println(hello.name)
    println(hello.greet())
}

Output:

devkuma
Hello