Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
Lære Overriding Methods | Object-Oriented Concepts in Kotlin
Kotlin Classes and Objects

bookOverriding Methods

Sveip for å vise menyen

Why Override Methods?

When you use inheritance in Kotlin, you often want subclasses to provide their own specific behavior for methods defined in a superclass. This is called overriding. Overriding allows you to change or extend the functionality of inherited methods so that each subclass can behave appropriately for its own context. For example, if you have a generic Shape class with a method to calculate the area, different shapes like circles and rectangles must each calculate their area differently. Overriding lets you implement this custom logic in each subclass.

Override Syntax

In Kotlin, you must explicitly mark a method in the superclass as open to allow it to be overridden. Then, in the subclass, you use the override keyword to provide a new implementation. This makes it clear which methods are intended to be customized by subclasses, and helps prevent accidental overrides or mistakes.

ShapeExample.kt

ShapeExample.kt

copy

In the code above, the Shape class defines an open method called area, which simply returns 0.0 by default. The Circle class inherits from Shape and uses the override keyword to replace the area method with its own calculation, using the formula for the area of a circle. When you call area on a Circle instance, Kotlin will use the overridden method in Circle rather than the default method in Shape. This demonstrates how subclasses can provide their own specific implementations for inherited methods, ensuring that each type of shape calculates its area correctly.

question mark

What does the override keyword do in Kotlin?

Velg det helt riktige svaret

Alt var klart?

Hvordan kan vi forbedre det?

Takk for tilbakemeldingene dine!

Seksjon 3. Kapittel 3

Spør AI

expand

Spør AI

ChatGPT

Spør om hva du vil, eller prøv ett av de foreslåtte spørsmålene for å starte chatten vår

Seksjon 3. Kapittel 3
some-alt