Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
Lära Inheritance Basics | Object-Oriented Concepts in Kotlin
Kotlin Classes and Objects

bookInheritance Basics

Svep för att visa menyn

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

VehicleExample.kt

copy

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.

question mark

Which keyword is used to allow a class to be inherited in Kotlin?

Vänligen välj det korrekta svaret

Var allt tydligt?

Hur kan vi förbättra det?

Tack för dina kommentarer!

Avsnitt 3. Kapitel 2

Fråga AI

expand

Fråga AI

ChatGPT

Fråga vad du vill eller prova någon av de föreslagna frågorna för att starta vårt samtal

Avsnitt 3. Kapitel 2
some-alt