Kotlin Abstract Class

Kotlin Abstract Class is one of the way to implement abstraction in Kotlin. Following is a sample of how a Kotlin Abstract Class looks.

abstract class Vehicle {
    // regular variable
    var name : String = "Not Specified"
    // abstract variable
    abstract var medium : String
    // regular function
    fun runsWhere() {
        println("The vehicle, $name, runs on $medium")
    }
    // abstract function
    abstract fun howItRuns()
}

*regular meaning the variable/function is initialized/defined.

About Kotlin Abstract Class

Let us consider following simple example that demonstrates the usage of Abstract class, and then draw the list of points about Koltin Abstract Class.

example.kt

/**
 * Abstract Class
 */
abstract class Vehicle {
    // regular variable
    var name : String = "Not Specified"
    // abstract variable
    abstract var medium : String
    // regular function
    fun runsWhere() {
        println("The vehicle, $name, runs on $medium")
    }
    // abstract function
    abstract fun howItRuns()
}

/**
 * inheriting abstract class
 */
class Aeroplane : Vehicle() {
    // override abstract variables and functions of the
    // abstract class that is inherited
    override var medium: String = "air"

    override fun howItRuns() {
        println("Aeroplane fly based on buoyancy force.")
    }

}

fun main(args: Array<String>) {
    var vehicle1 = Aeroplane()
    vehicle1.howItRuns()
}

Let us break down the above example, and analyze the code.

1. abstract keyword is used to declare an abstract class.

abstract class Vehicle { }

2. Abstract classes cannot be instantiated.

fun main(args: Array<String>) {
    var vehicle:Vehicle = Vehicle()
}
Error:(2, 27) Kotlin: Cannot create an instance of an abstract class

3. Abstract classes can be inherited.

class Aeroplane : Vehicle() { }

4. Variables and functions of an abstract class could be declared either as abstract or not.

class Aeroplane : Vehicle() { }

5. Abstract variables are not initialized. Abstract methods does not have an implementation.

// abstract variable
    abstract var medium : String

    // abstract function
    abstract fun howItRuns()

6. In the inherited class, unless it is also an abstract class, variables and functions, not declared as abstract are not mandatory to override. Abstract variables and abstract functions must be overridden.

class Aeroplane : Vehicle() {
    // override abstract variables and functions of the
    // abstract class that is inherited
    override var medium: String = "air"

    override fun howItRuns() {
        println("Aeroplane fly based on buoyancy force.")
    }
}

7. To override non-abstract methods, they must be declared open. You may refer Kotlin Inheritance for a detailed example.

ADVERTISEMENT

Conclusion

In this Kotlin Tutorial, we learned about Abstract Classes in Kotlin.