Abstract Classes in Kotlin
Creating an Abstract Class
We indicate an abstract class in Kotlin by using the abstract modifier
when defining the class. The modifier must be applied to the start of the
class definition and to the declarations of any specific abstract features.
For example, the Vehicle class described with UML earlier could be
defined in Kotlin like so:
abstract class Vehicle(var fuelLevel: Int) {
fun refuel(amount: Int) {
require(amount >= 0) { "Invalid fuel amount" }
fuelLevel += amount
}
abstract fun drive()
}
Try this out now:
-
The subdirectory
tasks/task16_2in your repository is an Amper project that you can use to experiment with defining abstract classes.Open the file
Vehicle.kt, in the project’ssrcsubdirectory. Add the definition ofVehicleshown above and save the file. -
Go to the project directory in a terminal window and check that the class compiles successfully, using
./amper build -
Try removing the
abstractmodifier at the start of the class definition. What error do you see when you try rebuilding the project? -
Reapply the
abstractmodifier to the start of the class definition, then remove the modifier on thedrive()method. What error do you see when you try rebuilding the project? -
Reapply the
abstractmodifier to thedrive()method.
Using an Abstract Class
Inheriting from an abstract class doesn’t look any different to inheriting from a regular concrete class. However, when you do so, you must either provide implementations of all the abstract features, or declare the subclass itself as abstract.
Let’s try this out:
-
Return to the Amper project in
task16_2. Edit the file namedCar.ktand add the following class definition:class Car(fuel: Int) : Vehicle(fuel) -
Try rebuilding the project with
./amper build. What error do you see? -
The error message suggests two possible fixes. Implement the first of them now by adding the
abstractmodifier to the definition ofCar. Check that this does, indeed, fix the compiler error. -
Now try the other fix. Modify
Carso that it looks like this:class Car(fuel: Int) : Vehicle(fuel) { fun drive() { println("Vrooom!") } }When you rebuild the project, you should see another error from the compiler.
-
Use the information from the compiler error message to make one final change to the class, fixing the error. Rebuild the project to verify that you have done this successfully.
-
Finally, edit the file
Main.kt. Add code to themain()function that creates aCarobject and invokes itsdrive()method. Verify that this program runs as expected, using./amper run