Kotlin Abstract Class

The abstract class is declared with the keyword abstract. This abstract class cannot be instantiated, it only inherited.

abstract class Account

An abstract class can have both abstract and non abstract methods and properties. The abstract methods and properties are preceded with the abstract keyword and they do not have opening and closing braces. So, all the abstract members do not contain abstract body and if a member function contains body than it does not behave as abstract.


abstract class Account{
	abstract fun withdraw()
}

Class inherit abstract class

abstract class Account{
    abstract fun withdraw()
}
class Holder: Account(){
    override fun withdraw() {
        println("Holder is withdrawing money.")
    }
}
fun main(args : Array<String>)  { 
    val obj1 = Holder()
    obj1.withdraw()
}
Output
Holder is withdrawing money.

In the above example, the class Holder is derived from the abstract class Account. In the main method, an object of class Holder is instantiated and withdraw method of abstract class Account is called.


Over ride non abstract member function in abstract class

open class Bank{
    open fun withdraw(){
        println("Holder need to withdraw money.")
    }
}
abstract class Account : Bank(){
    override abstract fun withdraw()
}
class Holder: Account(){
    override fun withdraw() {
        println("Holder is withdrawing money.")
    }
}
fun main(args : Array<String>)  { 
    val obj1 = Bank()
    obj1.withdraw()
    val obj2 = Holder()
    obj2.withdraw()
}
Output
Holder need to withdraw money.
Holder is withdrawing money.

In the above example, there is an open class name Bank and an abstract class Account. The class Holder is derived from the abstract class Account. In the main method, an object of the class Bank and an object of class Holder are instantiated. The withdraw method of Bank class is overridden in the abstract class Account.









Read more articles