Tools
Log in
English

Learn to codeJava

Java composition and static

Based on Java 17

When to pick composition over inheritance in Java, and what static does.

In one line

Composition means keeping another object in a field and handing work to it. static members belong to the class itself, with exactly one copy.

Why you need it

Writing class Car extends Engine because a car needs an engine claims that "a car is an engine". Every public engine method shows up on the car, and switching to an electric motor means tearing up the class tree.

When Car holds an Engine in a field, the engine becomes an inside part. It is easy to swap, and Car decides which methods the outside sees. Values every car shares, like the number of cars made, go in a static field.

Everyday picture

A car has an engine; it is not an engine. Just as a garage can replace only the engine, composition makes parts easy to swap. static is the production counter board at the factory gate: not one per car, one for the whole factory.

Example code

Main.java · 56 lines
class Engine {    private final int power;    private boolean running;     Engine(int power) {        this.power = power;    }     void start() {        running = true;    }     boolean isRunning() {        return running;    }     int power() {        return power;    }} class Car {    static final int MAX_SPEED = 180;    private static int made = 0;     private final String model;    private final Engine engine;     Car(String model, Engine engine) {        this.model = model;        this.engine = engine;        made++;    }     static int made() {        return made;    }     String drive() {        if (!engine.isRunning()) {            engine.start();        }        return model + " drives with " + engine.power() + "hp";    }} public class Main {    public static void main(String[] args) {        Car city = new Car("City", new Engine(90));        Car van = new Car("Van", new Engine(150));        System.out.println(city.drive());        System.out.println(van.drive());        System.out.println("Cars made: " + Car.made());        System.out.println("Speed limit: " + Car.MAX_SPEED);    }}

When to use it

  • "X has a Y" sounds right (an order has an address, a car has an engine) → composition
  • You want only some of a parent class’s methods → composition, not inheritance
  • Constants and counters shared by every object, helper methods that need no object (Math.max) → static

Many changing values in static fields make it hard to tell where they changed. Constants (static final) are fine; keep changing static values to the ones you truly need.

Common mistakes

Inheriting for reuse and exposing everything

A stack should only push and pop, but extending ArrayList also exposes set, add(0, ...) and the rest. Keep the list in a private field and write only the methods you need.

Wrong

import java.util.ArrayList; class Stack extends ArrayList<String> {    void push(String s) {        add(s);    }     String pop() {        return remove(size() - 1);    }} public class Main {    public static void main(String[] args) {        Stack st = new Stack();        st.push("a");        st.push("b");        st.set(1, "oops");        System.out.println(st.pop());    }}

When you run itoops

Fixed

import java.util.ArrayList;import java.util.List; class Stack {    private final List<String> items = new ArrayList<>();     void push(String s) {        items.add(s);    }     String pop() {        return items.remove(items.size() - 1);    }} public class Main {    public static void main(String[] args) {        Stack st = new Stack();        st.push("a");        st.push("b");        System.out.println(st.pop());    }}

When you run itb

Making a per-object value static

A static field exists once per class, so the last car overwrites the model of every other car. Values that differ per car belong in ordinary fields.

Wrong

class Car {    static String model;     Car(String model) {        Car.model = model;    }} public class Main {    public static void main(String[] args) {        Car a = new Car("City");        Car b = new Car("Van");        System.out.println(a.model + ", " + b.model);    }}

When you run itVan, Van

Fixed

class Car {    private final String model;     Car(String model) {        this.model = model;    }     String model() {        return model;    }} public class Main {    public static void main(String[] args) {        Car a = new Car("City");        Car b = new Car("Van");        System.out.println(a.model() + ", " + b.model());    }}

When you run itCity, Van

Using an object field in a static method

A static method runs without an object, so it cannot know which car’s model you mean. Drop static from methods that use object values.

Wrong

class Car {    private final String model = "City";     static String describe() {        return "Model: " + model;    }}

What javac sayserror: non-static variable model cannot be referenced from a static context

Fixed

class Car {    private final String model = "City";     String describe() {        return "Model: " + model;    }}

Check yourself

Question 1

Three cars are created. What does Car.made() print?

public class Main {    public static void main(String[] args) {        new Car("A", new Engine(70));        new Car("B", new Engine(80));        new Car("C", new Engine(90));        System.out.println(Car.made());    }}

Show the answer

Answer: 2. 3 made is static, so all cars share one field. The constructor ran three times, so it is 3, even though the cars were never stored in variables.

Question 2

Which code fits "an order has a delivery address"?

Show the answer

Answer: 2. class Order { private Address address; } "Has a" means composition: keep it in a field. An order is not an address, so inheritance does not fit.

Questions people ask

How do I choose between inheritance and composition?

If "B is an A" is always true, inherit. If "B has an A" fits, compose. When in doubt, choose composition.

When should a method be static?

When it uses no object fields, such as helpers like Math.max or List.of, or when it works with values that belong to the whole class.

Are static variables global variables?

They behave much like them. Changes from anywhere are hard to trace, so keep changing static values private and update them through methods.