Careeroza
Abstract Classes
What is an Abstract Class?
An abstract class cannot be instantiated. It can hold state and normal functions, plus abstract members that every subclass must implement. Abstract classes and members are open automatically.
Example
abstract class Account(val holder: String) {
var balance = 0.0
protected set
abstract val interestRate: Double // must be provided
abstract fun monthlyCharge(): Double
fun deposit(amount: Double) { balance += amount } // shared logic
fun summary() = "$holder: balance ${balance}, rate ${interestRate}%, charge ${monthlyCharge()}"
}
class SavingsAccount(holder: String) : Account(holder) {
override val interestRate = 3.5
override fun monthlyCharge() = if (balance < 10000) 50.0 else 0.0
}
class CurrentAccount(holder: String) : Account(holder) {
override val interestRate = 0.0
override fun monthlyCharge() = 200.0
}
fun main() {
val s = SavingsAccount("Asha"); s.deposit(5000.0)
val c = CurrentAccount("Ravi Traders"); c.deposit(250000.0)
println(s.summary())
println(c.summary())
// val a = Account("x") // error: cannot create an instance of an abstract class
}Output
Asha: balance 5000.0, rate 3.5%, charge 50.0 Ravi Traders: balance 250000.0, rate 0.0%, charge 200.0