Inheritance in Kotlin
What is Inheritance?
Inheritance is a fundamental concept in object-oriented programming that allows one class to inherit properties and methods from another class. In Kotlin, inheritance is used to promote code reusability and establish a relationship between classes.
Base Class and Derived Class
In Kotlin, a class that is inherited from is called a base class (or superclass), while the class that inherits from it is called a derived class (or subclass).
Declaring a Base Class
To declare a base class in Kotlin, simply use the `open` keyword before the class definition. This indicates that the class can be inherited from.
open class Animal {
fun eat() {
println("Eating...")
}
}
Creating a Derived Class
To create a derived class, use a colon followed by the base class name. The derived class can override methods from the base class.
class Dog : Animal() {
fun bark() {
println("Barking...")
}
}
Overriding Methods
To override a method from the base class, use the `override` keyword. Note that the method in the base class must be marked with `open`.
open class Animal {
open fun sound() {
println("Some sound")
}
}
class Dog : Animal() {
override fun sound() {
println("Barking")
}
}
Using Inheritance
To use the derived class, you can create an instance of it and call the inherited and overridden methods.
fun main() {
val dog = Dog()
dog.eat() // Calls the inherited method
dog.sound() // Calls the overridden method
}
Output:
Eating...
Barking
Conclusion
Inheritance is a powerful feature in Kotlin that helps in creating a hierarchical relationship between classes. By using inheritance, developers can write more reusable and maintainable code. Understanding how to implement inheritance effectively is crucial for mastering object-oriented programming in Kotlin.