Kotlin
Beginner
1 min read
Inheritance and Interfaces
Example
interface Drawable {
val color: String // abstract property
fun draw() // abstract method
fun describe() = "I am a ${color} drawable" // default impl
}
interface Resizable {
fun resize(factor: Double)
}
// open allows subclassing
open class Shape(override val color: String) : Drawable {
override fun draw() = println("Drawing a $color shape")
}
// Inherits Shape, implements Resizable
class Circle(color: String, var radius: Double)
: Shape(color), Resizable {
override fun draw() {
super.draw() // calls Shape.draw()
println(" (circle r=$radius)")
}
override fun resize(factor: Double) {
radius *= factor
}
}
// Abstract class — cannot be instantiated directly
abstract class Vehicle(val brand: String) {
abstract fun fuelType(): String
fun info() = "$brand runs on ${fuelType()}"
}
class ElectricCar(brand: String) : Vehicle(brand) {
override fun fuelType() = "electricity"
}
fun main() {
val c = Circle("red", 5.0)
c.draw()
println(c.describe())
c.resize(2.0)
println("New radius: ${c.radius}")
val car = ElectricCar("Tesla")
println(car.info())
}
Related Resources
Kotlin Reference
Complete tag & property list
Kotlin How-To Guides
Step-by-step practical guides
Kotlin Exercises
Practice what you've learned
More in Kotlin