Inheritance Basics
Stryg for at vise menuen
Introduction to inheritance
Inheritance is a fundamental concept in object-oriented programming that allows you to create new classes based on existing ones. This enables you to reuse code, organize related classes, and build complex systems from simpler building blocks.
What is Inheritance?
Inheritance lets you define a base class (sometimes called a superclass or parent class) and then create subclasses (or child classes) that inherit properties and methods from the base class. Subclasses can also introduce their own properties and methods, or modify the inherited ones.
Extending Classes in Kotlin
In Kotlin, classes are final by default, which means you cannot inherit from them unless you explicitly declare them as open. To create a subclass, you use the : symbol followed by the base class name after the subclass declaration.
VehicleExample.kt
In the code above, you see an open class Vehicle with a property brand and a method honk(). The Car class extends Vehicle by declaring class Car(brand: String, val model: String) : Vehicle(brand). This means that Car inherits the brand property and the honk() method from Vehicle. The Car class adds its own property model and a method displayInfo(). When you create an instance of Car, you can call both the inherited honk() method and the new displayInfo() method, demonstrating how subclassing works in Kotlin.
Tak for dine kommentarer!
Spørg AI
Spørg AI
Spørg om hvad som helst eller prøv et af de foreslåede spørgsmål for at starte vores chat