Keyboard shortcuts

Press or to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

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:

  1. The subdirectory tasks/task16_2 in your repository is an Amper project that you can use to experiment with defining abstract classes.

    Open the file Vehicle.kt, in the project’s src subdirectory. Add the definition of Vehicle shown above and save the file.

  2. Go to the project directory in a terminal window and check that the class compiles successfully, using

    ./amper build
    
  3. Try removing the abstract modifier at the start of the class definition. What error do you see when you try rebuilding the project?

  4. Reapply the abstract modifier to the start of the class definition, then remove the modifier on the drive() method. What error do you see when you try rebuilding the project?

  5. Reapply the abstract modifier to the drive() 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:

  1. Return to the Amper project in task16_2. Edit the file named Car.kt and add the following class definition:

    class Car(fuel: Int) : Vehicle(fuel)
    
  2. Try rebuilding the project with ./amper build. What error do you see?

  3. The error message suggests two possible fixes. Implement the first of them now by adding the abstract modifier to the definition of Car. Check that this does, indeed, fix the compiler error.

  4. Now try the other fix. Modify Car so 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.

  5. 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.

  6. Finally, edit the file Main.kt. Add code to the main() function that creates a Car object and invokes its drive() method. Verify that this program runs as expected, using

    ./amper run