Start learning free

LESSON 599 OF 635 · OBJECT-ORIENTED PROGRAMMING

Composition in Java in Java

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 Engine engine;

    public Car() {
        this.engine = new Engine();   // a Car has an Engine
    }

    public void 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 extends 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.

The field is private, as in Access Modifiers. The constructor creates the 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 in the constructor.

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 Java

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