Chapter 07Part II · Objects
Inheritance and Composition
In this chapter: how one class builds on another, what is and isn't inherited, the rules for overriding, why "has-a" often beats "is-a", and how Java 17's sealed classes let you say exactly who may extend a type.
Key points
class Car extends Vehicle: a class has one parent class. Every chain ends atjava.lang.Object.- Parent constructors always run first: each constructor begins with
this(...)orsuper(...), and the compiler insertssuper()if you write neither. - Fields are hidden (the reference type decides); methods are overridden (the object decides).
finalstops extension or overriding. Sealed classes and interfaces (Java 17) allow extension only by a listed set of types, which makesswitchexhaustive (Java 21).- Prefer composition (a class has another object) over inheritance unless the relationship is truly "is-a."
What inheritance gives you
class Car extends Vehicle means a Car is a Vehicle: it inherits the parent's fields and methods and can be used wherever a Vehicle is expected.
What's inherited, and what isn't:
| Member | Inherited? |
|---|---|
public and protected fields and methods |
Yes |
| Package-private members | Only if the subclass is in the same package |
private members |
No. They exist inside the object but the subclass can't name them. |
| Constructors | No. Each class declares its own. |
static members |
Accessible through the subclass, but not overridden |
The classic rule
"Rule → In Java, Object is the top-most class. Every class which has no parent extends Object."
That's why every object has toString, equals, hashCode and getClass.
Constructors in a hierarchy
public class ConstructorChain {
static class Vehicle {
Vehicle() { System.out.println("1. Vehicle()"); }
}
static class Car extends Vehicle {
Car(String model) { // compiler inserts super() here
System.out.println("2. Car(" + model + ")");
}
}
static class SportsCar extends Car {
SportsCar() {
super("GT"); // explicit call to a parent constructor
System.out.println("3. SportsCar()");
}
}
public static void main(String[] args) {
new SportsCar();
}
}
An object is built from the top down: Object, then Vehicle, then Car, then SportsCar. Each constructor's first act is to call its parent's.
The classic rule
"Rule → Every constructor of every child class has either this() or super() as its first line. If nothing is there, by default it goes to super()."
Still true, with one Java 25 refinement (Chapter 5): statements that don't use this may now come before that call.
One consequence catches people out: if the parent has no no-argument constructor, every child constructor must call super(...) explicitly, or the class won't compile.
Hiding vs. overriding
public class HidingVsOverriding {
static class Parent {
String name = "parent field";
String name() { return "parent method"; }
}
static class Child extends Parent {
// hides Parent.name
String name = "child field";
// overrides Parent.name()
@Override String name() { return "child method"; }
String both() {
return name + " / " + super.name + " / " + super.name();
}
}
public static void main(String[] args) {
Parent p = new Child();
System.out.println(p.name); // fields: chosen by the reference type
System.out.println(p.name()); // methods: chosen by the object
System.out.println(new Child().both());
}
}
- A field with the same name in the child hides the parent's field. Which one you get depends on the reference type:
p.namereadsParent.namebecausepis declaredParent. - A method with the same signature overrides the parent's. Which one runs depends on the object:
p.name()runsChild.name(). super.nameandsuper.name()reach the parent's versions from inside the child.
In the Java 7 era, the first was often called data hiding and the second method overriding. Hiding fields is legal but confusing, and it's almost always a mistake. Keep fields private and the problem disappears.
Overriding rules
An override must keep the same signature, may return a subtype (covariant return), may not throw new or broader checked exceptions, and may not reduce visibility:
public class WeakerAccess {
static class Parent { public void greet() { } }
static class Child extends Parent {
@Override void greet() { } // package-private is weaker than public
}
}
WeakerAccess.java:4: error: greet() in Child cannot override greet() in Parent
@Override void greet() { } // package-private is weaker than public
^
attempting to assign weaker access privileges; was public
1 error
The reason is substitutability: code holding a Parent reference may call greet(), so every subclass must allow that call.
final: closing the door
final means "can't change" in three places:
- A
finalclass can't be extended.Stringand all the wrapper classes are final. - A
finalmethod can't be overridden. - A
finalvariable can be assigned only once. Afinalfield must be assigned by the end of every constructor; astatic finalfield is a constant.
The classic rule
"Rule → When you make any local variable final, its value can't be changed. When you make any class final, it can't be inherited."
Java 8 added a softer cousin, effectively final: a local variable that's never reassigned can be used by lambdas and inner classes without the keyword (Chapter 10).
Sealed classes: a middle ground (Java 17)
For years a class was either open to everyone or final to everyone. Sealed types (JEP 409) list exactly which types may extend them:
public class SealedShapes {
sealed interface Shape permits Circle, Square, Polygon { } // Java 17
record Circle(double radius) implements Shape { }
record Square(double side) implements Shape { }
// reopened for extension
non-sealed static class Polygon implements Shape { }
static class Hexagon extends Polygon { }
static String name(Shape s) {
// no default: the compiler
return switch (s) {
// knows every Shape subtype
case Circle c -> "circle r=" + c.radius();
case Square sq -> "square side=" + sq.side();
case Polygon p ->
"polygon (" + p.getClass().getSimpleName() + ")";
};
}
public static void main(String[] args) {
Shape[] shapes = { new Circle(1.5), new Square(2), new Hexagon() };
for (Shape s : shapes) System.out.println(name(s));
}
}
sealed … permits Circle, Square, Polygonnames the only allowed direct subtypes.- Each permitted subtype must say how it continues:
final(records are implicitly final),sealedwith its own list, ornon-sealedto reopen the hierarchy below it. - Because the compiler knows every subtype, a
switchover aShapewith a case for each one is exhaustive, and needs nodefault. Add a new shape and every suchswitchfails to compile until you handle it, which is exactly what you want.
Anything else is rejected:
public class NotPermitted {
sealed interface Shape permits Circle { }
record Circle(double r) implements Shape { }
// not in the permits list
record Triangle(double base) implements Shape { }
}
NotPermitted.java:5: error: class is not allowed to extend sealed class: Shape (as it is not listed in its 'permits' clause)
record Triangle(double base) implements Shape { }
^
1 error
Composition over inheritance
Classic object-oriented design distinguishes association, aggregation and composition: an object that uses another, one that has another that can live on its own, and one that owns another that lives and dies with it. Modern Java style simplifies the advice: when a class just needs another class's abilities, hold an instance of it rather than extending it.
import java.util.ArrayList;
import java.util.List;
public class Composition {
// Inheritance would say "a Playlist IS-A ArrayList" and expose
// add/remove/clear to everyone. Composition says "a Playlist HAS-A
// list" and exposes only what makes sense.
static class Playlist {
private final List<String> songs = new ArrayList<>();
void add(String song) { if (!songs.contains(song)) songs.add(song); }
int size() { return songs.size(); }
// Java 10: read-only copy
List<String> songs() { return List.copyOf(songs); }
}
public static void main(String[] args) {
Playlist p = new Playlist();
p.add("Duke's Theme");
// duplicate ignored: the Playlist enforces its own rule
p.add("Duke's Theme");
p.add("Coffee Break");
System.out.println(p.size() + " " + p.songs());
}
}
Had Playlist extended ArrayList, every caller could add duplicates, clear it, or set any element, and Playlist could never enforce its own rules. Inheritance is right when the subclass truly is a specialized parent and every parent operation makes sense for it.
Go deeper in the complete edition
This page is the focused edition. The complete edition of this chapter on GitHub adds the deep dives, puzzles, exercises and interview questions, with every sample ready to run.
Summary
- One parent class per class, ending at
Object. Constructors chain from the top down. - Fields are hidden by reference type; methods are overridden by object type. Overrides can't narrow access.
finalcloses a class, method or variable. Sealed types (Java 17) close a hierarchy to a known list, enabling exhaustiveswitch(Java 21).- Prefer composition when "is-a" isn't really true.
Next: Chapter 8 covers abstraction: abstract classes and interfaces, and how interfaces gained default, static and private methods.