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.
Java code does not run on this page. Compile your changed code with javac on your own computer.
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.
Answer: 2. 3made 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.