English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

Kotlin Abstract Classes (Abstract)

In this article, you will learn about abstract classes and how to implement abstract classes in Kotlin (with examples).

Like Java, the abstract keyword is used to declare abstract classes in Kotlin. You cannot instantiate abstract classes (you cannot create objects of abstract classes). However, you can inherit subclasses from them.

Unless you explicitly use the abstract keyword to abstract it, the members (properties and methods) of the abstract class are non-abstract. Let's take an example:

abstract class Person {
    
    var age: Int = 40
    fun displaySSN(ssn: Int) {
        println("My social security number is: $ssn.")
    }
    abstract fun displayJob(description: String)
}

Here,

  • Create an abstract class Person. You cannot create an object of this class.

  • This class has non-abstract properties age and non-abstract methods displaySSN(). If you need to override these members in subclasses, you should mark them with the open keyword.

  • This class has an abstract method displayJob(). It has no implementation and must be overridden in its subclasses.

Note:Abstract classes are always open. You do not need to explicitly use the open keyword to inherit subclasses from them.

Example: Kotlin abstract class and methods

abstract class Person(name: String) {
    init {
        println("My name is $name.")
    }
    fun displaySSN(ssn: Int) {
        println("My social security number is $ssn.")
    }
    abstract fun displayJob(description: String)
}
class Teacher(name: String): Person(name) {
    override fun displayJob(description: String) {
        println(description)
    }
}
fun main(args: Array<String>) {
    val jack = Teacher("Jack Smith")
    jack.displayJob("I am a math teacher.")
    jack.displaySSN(23123)
}

When running the program, the output is:

My name is Jack Smith.
I am a math teacher.
My social security number is 23123.

In this case, the Teacher class inherits from the abstract class Person

An instance of the Teacher class named jack is created. When creating the main constructor, we pass 'Jack Smith' as a parameter to it. This will execute the initialization block of the Person class.

Then, use the Jack object to call the displayJob() method. Note that the displayJob() method is declared as abstract in the base class and overridden in the derived class.
Finally, use the Jack object to call the displaySSN() method. This method is non-abstract and is declared in the Person class (not in the Teacher class).

Related Knowledge: Kotlin Interface

Kotlin interfaces are similar to abstract classes. However, interfaces cannot store state, while abstract classes can.

That is, an interface may have properties, but they must be abstract or must provide an accessor implementation. However, the properties of an abstract class do not have to be abstract.