Start learning free

LESSON 603 OF 639 · OBJECT-ORIENTED PROGRAMMING

Composition in Kotlin in Kotlin

Lesson

TL ; DR:

A class can keep an object of another class in a field. It passes work on to that object. A Car has an Engine. This is composition.


class Car {
    private val engine = Engine()   // a Car has an Engine

    fun start() {
        engine.start()   // the Car asks its Engine
    }
}


Full lesson:

Things are often made of other things. A car has an engine. A phone has a battery.

Code works the same way. One class keeps an object of another class in a field. This is called composition.

The outer object passes some work on to its part. Car's start just calls the engine's start. This is called delegation.

Has-a or is-a?

Inheritance is for "is a". A Puppy is a Dog, so Puppy inherits from Dog. A Car is not an Engine. With class Car : Engine(), every engine method would become a car method. A car has an engine, so Car keeps one in a field. It passes on only what it chooses, like start.

Why it helps

  • The engine stays private. Code outside talks to the car, never to the engine.
  • Each class does one job. Engine knows how to start. Car knows its name and how to drive.
  • A part can be replaced. A car with a new engine is still the same car.

A property in the class body gets its value when each car is created. So private val engine = Engine() gives every car its own engine.


Your task

The Engine class is ready. Car already has a name and a drive method.

Give Car a private Engine field. Create the engine where you declare the field.

Then write Car's start method. It calls the engine's start.

The program makes a car named "Rocket". It starts the car, then drives it.

Expected output:

Engine started
Rocket is driving
STEP 1 OF 3
    Ctrl + Enter to check

    Composition in Kotlin

    Keep going with Kotlin500+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free