0
0
Kotlinprogramming~30 mins

Open classes and methods in Kotlin - Mini Project: Build & Apply

Choose your learning style9 modes available
Open Classes and Methods in Kotlin
📖 Scenario: You are creating a simple app that manages vehicles. You want to allow future changes by letting other developers add new types of vehicles or change how existing ones behave.
🎯 Goal: Learn how to make a class and its method open for extension in Kotlin. You will create an open class, then override its method in a subclass, and finally print the results.
📋 What You'll Learn
Create an open class named Vehicle with an open method drive() that returns a string.
Create a subclass named Car that inherits from Vehicle and overrides the drive() method.
Print the output of calling drive() on both Vehicle and Car objects.
💡 Why This Matters
🌍 Real World
Open classes and methods let developers design flexible software that can grow and change without rewriting existing code.
💼 Career
Understanding open classes is important for Kotlin developers working on apps that require customization and extension, such as Android apps or libraries.
Progress0 / 4 steps
1
Create an open class with an open method
Create an open class called Vehicle with an open method named drive() that returns the string "Driving a vehicle".
Kotlin
Need a hint?

Use the open keyword before the class and the method to allow them to be extended and overridden.

2
Create a subclass that overrides the method
Create a class called Car that inherits from Vehicle and overrides the drive() method to return the string "Driving a car".
Kotlin
Need a hint?

Use class Car : Vehicle() to inherit and override fun drive() to change the method.

3
Create objects and call the methods
Create a variable vehicle as an instance of Vehicle and a variable car as an instance of Car. Call the drive() method on both and store the results in variables vehicleDrive and carDrive.
Kotlin
Need a hint?

Create instances using val variableName = ClassName() and call methods with variable.method().

4
Print the results
Print the variables vehicleDrive and carDrive each on a new line.
Kotlin
Need a hint?

Use println() to show the text on the screen.