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

bookInheritance Basics

Glissez pour afficher le menu

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?

Sélectionnez la réponse correcte

Tout était clair ?

Comment pouvons-nous l'améliorer ?

Merci pour vos commentaires !

Section 3. Chapitre 2

Demandez à l'IA

expand

Demandez à l'IA

ChatGPT

Posez n'importe quelle question ou essayez l'une des questions suggérées pour commencer notre discussion

Section 3. Chapitre 2
some-alt