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

bookInheritance Basics

Scorri per mostrare il 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?

Seleziona la risposta corretta

Tutto è chiaro?

Come possiamo migliorarlo?

Grazie per i tuoi commenti!

Sezione 3. Capitolo 2

Chieda ad AI

expand

Chieda ad AI

ChatGPT

Chieda pure quello che desidera o provi una delle domande suggerite per iniziare la nostra conversazione

Sezione 3. Capitolo 2
some-alt