Kotlin - Abstract Class Example

A class which is declared with abstract keyword is known as abstract class. An abstract class cannot be instantiated. Means, we cannot create an object of an abstract class. The method and properties of an abstract class are non-abstract unless they are explicitly declared as abstract.

Declaration of abstract class

Abstract classes are partially defined classes, methods, and properties which are no implementation but must be implemented into derived class.
abstract class A {  
var x = 0  
    abstract fun doSomething()  
}  

Kotlin Abstract Class Example

In this example, an abstract class Bank that contains an abstract function simpleInterest() accepts three parameters principle, rate,and time. The class SBI and PNB provides the implementation of simpleInterest() function and returns the result.
package net.javaguides.kotlin.examples

abstract class Bank {
    abstract fun simpleInterest(principle: Int, rate: Double, time: Int): Double
}

class SBI: Bank() {
    override fun simpleInterest(principle: Int, rate: Double, time: Int): Double {
        return (principle * rate * time) / 100
    }
}

class PNB: Bank() {
    override fun simpleInterest(principle: Int, rate: Double, time: Int): Double {
        return (principle * rate * time) / 100
    }
}

fun main(args: Array < String > ) {
    var sbi: Bank = SBI()
    val sbiint = sbi.simpleInterest(1000, 5.0, 3)
    println("SBI interest is $sbiint")
    var pnb: Bank = PNB()
    val pnbint = pnb.simpleInterest(1000, 4.5, 3)
    println("PNB interest is $pnbint")
}
Output:
SBI interest is 150.0
PNB interest is 135.0

Comments