In Kotlin, classes cannot be inherited, because they are marked as final in default. To make a class inheritable, add the reserved word open
before the word class
.
open class Keyboard{}
Inheritance Declaration
fun main() {
Mechanical()
}
class Mechanical: Keyboard("Mechanical")
open class Keyboard (type: String){
init {
print("Its a $type Keyboard")
}
}---------
OUTPUT:
Its a Mechanical Keyboard
Here we declared an inheritable class Keyboard
with a primary constructor type
then we extend this open class using the :
symbol to the Mechanical
class header so that it can inherit whatever inside theKeyboard
open class.
Overriding Methods and Variables
fun main() {
val mechanical = Mechanical()
mechanical.description()
mechanical.comment()
}
open class Keyboard{
open var type: String = "Normal"
open var keys: Int = 104
open fun description(){}
fun comment(){
println("Awesome!")
}
}
class Mechanical: Keyboard(){
override var type: String = "Mechanical"
override var keys: Int = 88
override fun description() {
println("A $type keyboard with $keys keys")
}
}
Aside from the method description()
, you can also override a variable
using the open
keyword.
Inheritance is useful if you wish to have a set of objects with the same state or behavior to avoid the repetitive declaration. For example, an animal has the same characteristics with the other animals, like color, size, sound, etc.
I’m still learning, please leave a comment if there’s something I need to improve/learn/elaborate. Arigato!