Kotlin Super Keyword Tutorial šŸŽÆ

beginner
8 min

Kotlin Super Keyword Tutorial šŸŽÆ

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.

What is the 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.

Accessing Superclass Methods and Fields

Let's start with an example. Suppose we have a Vehicle superclass with a brand field and a start method.

kotlin
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.

kotlin
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 Superclass Methods

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.

kotlin
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.

Quiz Time!

Quick Quiz
Question 1 of 1

What does the `super` keyword do in Kotlin?

Wrapping Up

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!