Inheritance in Kotlin - Extending Classes


Inheritance is a fundamental concept in object-oriented programming, and Kotlin provides robust support for creating hierarchies of classes. In this guide, we'll explore how to extend classes, inherit properties and methods, and leverage the power of inheritance in Kotlin.


Defining a Superclass

A superclass (or base class) is the class that you want to extend. In Kotlin, you can define a superclass like this:

open class Vehicle {
var color: String = ""
fun start() {
println("Engine started.")
}
}

The open keyword is used to make the class open for inheritance.


Creating a Subclass

A subclass is a class that inherits from a superclass. You can create a subclass using the : symbol to specify the superclass you want to extend:

class Car : Vehicle() {
fun drive() {
println("Car is moving.")
}
}

The subclass Car inherits the properties and methods of the Vehicle superclass. You can also add new properties and methods specific to the subclass.


Using Inherited Features

You can use the inherited properties and methods from the superclass within the subclass:

val myCar = Car()
myCar.color = "Red"
myCar.start()
myCar.drive()

Overriding Methods

You can override methods from the superclass in the subclass to provide custom behavior:

open class Animal {
open fun speak() {
println("Animal speaks.")
}
}
class Dog : Animal() {
override fun speak() {
println("Dog barks.")
}
}

Conclusion

Inheritance in Kotlin allows you to create class hierarchies, reuse code, and build on existing classes. By extending a superclass to create a subclass, you can inherit and override properties and methods, providing a powerful mechanism for code organization and customization.


Happy coding!