final and Constructor Order

The final Keyword

Used onMeaningExample
variablevalue cannot be reassignedfinal int MAX = 5;
methodcannot be overriddenfinal void pay()
classcannot be extendedfinal class String

Note: String, Integer and other wrapper classes are final, so nobody can change their behaviour by subclassing.

Parent Constructors Run First

Example

Creating a grandchild runs constructors from the top of the hierarchy down.

public class Main {
    public static void main(String[] args) {
        new ElectricCar();
    }
}

class Vehicle {
    Vehicle() { System.out.println("1. Vehicle"); }
}

class Car extends Vehicle {
    Car() { System.out.println("2. Car"); }
}

class ElectricCar extends Car {
    ElectricCar() { System.out.println("3. ElectricCar"); }
}

Output

1. Vehicle
2. Car
3. ElectricCar

Composition over Inheritance

Use inheritance only for true IS-A relationships. When a class just uses another (HAS-A), hold it as a field instead. A Car HAS-A Engine; it is not an engine.

class Engine {
    void start() { System.out.println("Engine on"); }
}

class Car {
    private final Engine engine = new Engine();   // composition

    void start() {
        engine.start();
    }
}