Welcome to CodeYourCraft's Kotlin Super Keyword Tutorial! In this lesson, we'll explore the concept of the super keyword in Kotlin, a modern programming language that's gaining popularity in the development world. š” Pro Tip: Understanding the super keyword will help you navigate inheritance in Kotlin more effectively.
super keyword?In simple terms, the super keyword allows a subclass to access and override the methods, properties, and fields of its superclass. It helps to create a hierarchical class structure and enables code reuse.
š Note: The super keyword can be used when a subclass is overriding a method or accessing a field from the superclass.
Let's start with an example. Suppose we have a Vehicle superclass with a brand field and a start method.
open class Vehicle(val brand: String) {
fun start() {
println("$brand is starting...")
}
}Now, let's create a Car subclass that inherits from Vehicle. We'll override the start method to provide more specific behavior.
class Car(brand: String) : Vehicle(brand) {
override fun start() {
println("Engine starting in $brand...")
super.start() // Calling the superclass's start method
}
}In the above example, we're using the super keyword to call the start method from the Vehicle superclass within the Car subclass.
Overriding a method means providing a new implementation for a method that already exists in the superclass. Let's create a Bike subclass and override the start method.
class Bike(brand: String) : Vehicle(brand) {
override fun start() {
println("$brand bike's engine is starting...")
}
}Now, when you call the start method on a Bike object, it will use the implementation provided in the Bike class instead of the one in the Vehicle class.
What does the `super` keyword do in Kotlin?
In this tutorial, you learned about the Kotlin super keyword, its purpose, and how to use it to access and override methods, properties, and fields from the superclass. Practice using the super keyword in your own projects, and you'll master the art of inheritance in Kotlin. š Happy coding!