IntermediateLesson 8 of 16
Classes, Properties & Interfaces – Kotlin
Primary constructor, properties, inheritance with open, and interfaces.
The primary constructor sits right in the class header. With val or var in front of a parameter, it immediately becomes a property. In the init block you validate values. Kotlin properties automatically have getters and setters – without boilerplate.
class Konto(val inhaber: String, startSaldo: Double) {
var saldo: Double = startSaldo
private set // can only be changed inside the class
init {
require(startSaldo >= 0) { "Initial balance must not be negative" }
}
fun einzahlen(betrag: Double) {
require(betrag > 0) { "Amount must be positive" }
saldo += betrag
}
override fun toString() = "$inhaber: $saldo"
}
val k = Konto("Ada", 100.0)
k.einzahlen(50.0)
println(k) // Ada: 150.0
// k.saldo = 5.0 // Error: private setClasses in Kotlin are final by default. For inheritance, you mark the base class and overridable members with open (or abstract); subclasses use override.
abstract class Tier(val name: String) {
abstract fun sprich(): String
fun vorstellen() = println("$name: ${sprich()}")
}
class Hund(name: String) : Tier(name) {
override fun sprich() = "Woof!"
}
open class Katze(name: String) : Tier(name) {
override fun sprich() = "Meow!"
}
listOf(Hund("Rex"), Katze("Tom")).forEach { it.vorstellen() } // Rex: Woof! Tom: Meow!Interfaces may contain properties and methods with a default implementation. A class can implement many interfaces. Computed properties have their own getter:
interface Bezahlbar {
val preis: Double
fun mitVersand() = preis + 4.5
}
class Buch(override val preis: Double) : Bezahlbar {
val istTeuer: Boolean get() = preis > 50 // computed on every access
}
val b = Buch(10.0)
println(b.mitVersand()) // 14.5
println(b.istTeuer) // falseWarningIf you forget
open, the compiler reports "This type is final, so it cannot be inherited from". That is intentional: inheritance should be a deliberate choice.TipVisibilities:
public (default), private, protected, internal (only within the same module). Prefer composition and interfaces over deep inheritance hierarchies.