Kotlin Tutorial
Kotlin Classes
Inheritance:
In Kotlin, we can inherit properties and functions of one class from another class. In the concept of inheritance we got two categories:
- Superclass: The parent class from which a class is inherited.
- Subclass: The child class that inherits from another class.
In Kotlin, the classes are final by default – they cannot be inherited. To make them inheritable there is a keyword open:
In the example below we have 2 classes ParentClass and ChildClass, we inherit the ChildClass from ParentClass; but you will see the compile time error ( This type is final, so it cannot be inherited from ).
class ParentClass() {}
class ChildClass : ParentClass() {}
To overcome this error mark the ParentClass with the keyword open like in the example below:
open class ParentClass() {}
class ChildClass : ParentClass() {}
Now the error will be gone.
Let’s get things more interesting by creating a function in ParentClass and calling it from the ChildClass instance (object).
fun main(args: Array) {
val c1 = ChildClass()
c1.someActivity()
}
open class ParentClass() {
fun someActivity() {
println("Parent class activity")
}
}
class ChildClass : ParentClass() {}
The code above outputs:
Parent class activity
Why Inheritance:
The concept of inheritance is useful for reusability of code like reuse the properties and the functions of an already existing class when you create a new class and inherit it.