In Kotlin, classes are final by default which means they cannot be inherited from.
To allow inheritance on a class, use the open
keyword.
open class Thing {
// I can now be extended!
}
Note: abstract classes, sealed classes and interfaces will be
open
by default.
open class BaseClass {
val x = 10
}
class DerivedClass: BaseClass() {
fun foo() {
println("x is equal to " + x)
}
}
fun main(args: Array<String>) {
val derivedClass = DerivedClass()
derivedClass.foo() // prints: 'x is equal to 10'
}
open class Person {
fun jump() {
println("Jumping...")
}
}
class Ninja: Person() {
fun sneak() {
println("Sneaking around...")
}
}
fun main(args: Array<String>) {
val ninja = Ninja()
ninja.jump() // prints: 'Jumping...'
ninja.sneak() // prints: 'Sneaking around...'
}
abstract class Car {
abstract val name: String;
open var speed: Int = 0;
}
class BrokenCar(override val name: String) : Car() {
override var speed: Int
get() = 0
set(value) {
throw UnsupportedOperationException("The car is bloken")
}
}
fun main(args: Array<String>) {
val car: Car = BrokenCar("Lada")
car.speed = 10
}
interface Ship {
fun sail()
fun sink()
}
object Titanic : Ship {
var canSail = true
override fun sail() {
sink()
}
override fun sink() {
canSail = false
}
}
Parameter | Details |
---|---|
Base Class | Class that is inherited from |
Derived Class | Class that inherits from Base Class |
Init Arguments | Arguments passed to constructor of Base Class |
Function Definition | Function in Derived Class that has different code than the same in the Base Class |
DC-Object | ”Derived Class-Object“ Object that has the type of the Derived Class |