Java Inheritance
extends, super, overriding, the Object root — and when to prefer composition instead.
Extending a Class
A class declares its superclass with extends. Java allows exactly one superclass per class (single inheritance); a class that names none extends java.lang.Object. The subclass inherits every accessible member and can call inherited methods as if they were its own.
Constructors and super
Constructors are not inherited. A subclass constructor must first initialize the superclass part of the object, by calling super(...) as its first statement. If it does not, the compiler inserts a call to the superclass's no-argument constructor — and reports an error if there is none. Construction therefore always runs from the top of the hierarchy down, as the output below shows.
// A subclass extends a superclass: it inherits members and may override methods.
class Account {
protected final String owner; // visible to subclasses
protected double balance;
Account(String owner, double balance) {
this.owner = owner;
this.balance = balance;
System.out.println("Account constructor");
}
void deposit(double amount) {
balance += amount;
}
String describe() {
return owner + ": " + balance;
}
}
class SavingsAccount extends Account {
private final double rate;
SavingsAccount(String owner, double balance, double rate) {
super(owner, balance); // must be the first statement
this.rate = rate;
System.out.println("SavingsAccount constructor");
}
void addInterest() {
deposit(balance * rate); // inherited method
}
@Override
String describe() { // replaces the inherited version
return super.describe() + " (savings, rate " + rate + ")";
}
}
class InheritBasics {
public static void main(String[] args) {
SavingsAccount s = new SavingsAccount("Ana", 1000.0, 0.05);
s.addInterest();
System.out.println(s.describe());
Account a = s; // upcast: a SavingsAccount is an Account
System.out.println(a.describe()); // still calls the overriding method
}
}
Output:
Account constructor
SavingsAccount constructor
Ana: 1050.0 (savings, rate 0.05)
Ana: 1050.0 (savings, rate 0.05)
What a Subclass Can See
| Modifier | Same class | Same package | Subclass in another package | Everywhere |
|---|---|---|---|---|
private | yes | no | no | no |
| (none) package-private | yes | yes | no | no |
protected | yes | yes | yes | no |
public | yes | yes | yes | yes |
Private members still exist inside a subclass object, but subclass code cannot name them; it reaches them only through inherited methods. Keep fields private by default and expose what subclasses need through protected methods.
Overriding Methods
A subclass overrides an inherited method by declaring one with the same name and parameter types. The overriding method may return a subtype of the original return type, and may not reduce visibility (a public method cannot become protected). Inside it, super.method() calls the inherited version, as describe() does above.
Always Write @Override
The @Override annotation asks the compiler to confirm that the method really overrides something. Without it, a typo such as tostring() or a wrong parameter type silently creates a new method, and the inherited one keeps running. See Annotations for the other compiler-checked annotations.
Dynamic Dispatch
The last two lines of the example call describe() through a variable of type Account, yet the SavingsAccount version runs. Java chooses the method to call from the object's runtime class, not from the variable's declared type. This is the basis of polymorphism, explored in Abstraction. Static methods and fields are not dispatched this way: they belong to the class, and a subclass can only hide them.
The Object Class
Methods Every Object Has
java.lang.Object is the root of every class hierarchy, so every object has its methods. Three of them are worth overriding in classes that represent values:
toString()— the text shown byprintln, string concatenation and debuggers.equals(Object)— logical equality. The default compares identity, like==.hashCode()— must return equal values for equal objects, or hash-based collections such asHashSetandHashMapwill fail to find them.
equals and hashCode Together
// Every class extends Object; override equals, hashCode and toString together.
import java.util.HashSet;
import java.util.Objects;
import java.util.Set;
class Point {
private final int x, y;
Point(int x, int y) { this.x = x; this.y = y; }
@Override
public boolean equals(Object other) {
if (this == other) return true;
if (!(other instanceof Point p)) return false; // pattern matching instanceof
return x == p.x && y == p.y;
}
@Override
public int hashCode() { return Objects.hash(x, y); } // equal objects, equal hash
@Override
public String toString() { return "Point(" + x + ", " + y + ")"; }
}
class ObjectMethods {
public static void main(String[] args) {
Point a = new Point(1, 2), b = new Point(1, 2);
System.out.println(a == b); // false: two different objects
System.out.println(a.equals(b)); // true: same value
Set<Point> set = new HashSet<>();
set.add(a);
System.out.println(set.contains(b)); // true only because hashCode is consistent
System.out.println(a); // println calls toString()
}
}
Output:
false
true
true
Point(1, 2)
Override equals and hashCode together, always. For simple data carriers, a record generates all three methods for you.
Designing with Inheritance
Inheritance models an is-a relationship: a savings account is an account, and every rule that holds for accounts must hold for it. When that is not strictly true, inheritance causes bugs that are hard to see.
final Classes and Methods
Marking a class final prevents any subclass; marking a method final prevents overriding it. String and the wrapper classes such as Integer are final, which is why their behavior can be relied on everywhere. Make a class final unless you have designed and documented it for extension; to allow only specific subclasses, use sealed classes.
Prefer Composition When in Doubt
If a class only needs to use another class's behavior, hold an instance of it as a field instead of extending it. A Stack built on a private ArrayList exposes only push and pop; a Stack that extends ArrayList also exposes add(index, item), which breaks stack order. Composition keeps the public surface small and lets you change the implementation later. To share a type without sharing implementation, use interfaces, which a class may implement in any number.
Practice
Exercises
- Add a
CheckingAccountwith an overdraft limit that overrides a newwithdrawmethod, and verify that aSavingsAccountcannot be overdrawn. - Remove
@Overridefromdescribe(), rename it todescibe(), and observe what prints — then restore the annotation and read the compiler error. - Give
Pointaequalsoverride but deletehashCode, and predict, then check, whatset.contains(b)prints.