Inheritance and Polymorphism in Java
Inheritance lets a class reuse and extend another class, and polymorphism lets code written for the parent type work with any subclass, calling each object's own version of a method. Together they are the core of object-oriented Java, and also the source of some of its most subtle bugs. This page shows how method calls are dispatched, the order in which objects are built, the rules for overriding, and why composition is often the safer choice.
Contents
Inheritance and polymorphism in a nutshell
When class Manager extends EmployeeManagerEmployeeObject
Polymorphism means that a variable of the parent type can hold any subclass object, and calling an overridden method runs the version of the object's actual class. This is dynamic dispatch: the method is chosen when the program runs, not when it compiles.
| Member | Inherited? | Notes |
|---|---|---|
| Public and protected fields and methods | Yes | Usable directly in the subclass |
| Package-private members | Only if in the same package | |
| Private fields and methods | Present in the object, but not accessible | Reach them through the parent's methods |
| Constructors | No | Each class declares its own and calls super(...) |
| Static methods | Accessible, but hidden rather than overridden | Chosen by the declared type |
Dynamic dispatch and super
The program builds a payroll with one ordinary employee and one manager whose pay adds a bonus. The list is declared as List<Employee>
import java.util.List;
public class Dispatch {
static class Employee {
protected final String name;
protected final double baseSalary;
Employee(String name, double baseSalary) {
this.name = name;
this.baseSalary = baseSalary;
System.out.println(" Employee constructor for " + name);
}
double pay() {
return baseSalary;
}
String title() {
return "Employee";
}
@Override
public String toString() {
return String.format("%-9s %-6s %8.2f", title(), name, pay());
}
}
static class Manager extends Employee {
private final double bonus;
Manager(String name, double baseSalary, double bonus) {
super(name, baseSalary); // must be the first statement
this.bonus = bonus;
System.out.println(" Manager constructor for " + name);
}
@Override
double pay() {
return super.pay() + bonus; // reuse the parent's logic
}
@Override
String title() {
return "Manager";
}
}
public static void main(String[] args) {
System.out.println("constructing:");
List<Employee> staff = List.of(
new Employee("Ann", 4000),
new Manager("Bo", 5000, 1500));
System.out.println("payroll:");
double total = 0;
for (Employee e : staff) { // declared type Employee...
System.out.println(" " + e); // ...but each object's own methods run
total += e.pay();
}
System.out.printf("total %.2f%n", total);
}
}
Output:
constructing:
Employee constructor for Ann
Employee constructor for Bo
Manager constructor for Bo
payroll:
Employee Ann 4000.00
Manager Bo 6500.00
total 10500.00
- Creating Bo ran the
constructor first, then theEmployee one:Manager must be the first statement, so the parent part of an object is always built before the child part.super(name, baseSalary) - The loop variable is an
, yet Bo's line says "Manager" and 6,500.00:Employee andtitle() ran thepay() versions. EvenManager , written once intoString , called the overridden methods.Employee calls the parent's version from inside the override, so the manager's pay reuses the base salary logic and adds to it.super.pay()- This is what polymorphism buys: the payroll loop never changes when new kinds of employees are added.
Overloading versus overriding
Overloading (same name, different parameter types) and overriding (same signature in a subclass) look similar but are resolved at different times. The program calls both through a variable declared as AnimalDog
public class OverloadVsOverride {
static class Animal {
String sound() {
return "...";
}
static String kind() {
return "animal";
}
}
static class Dog extends Animal {
@Override
String sound() { // overriding: chosen at run time
return "woof";
}
static String kind() { // hiding: chosen at compile time
return "dog";
}
}
// Overloads: chosen at compile time from the DECLARED argument type
static String greet(Animal a) {
return "greet(Animal)";
}
static String greet(Dog d) {
return "greet(Dog)";
}
public static void main(String[] args) {
Animal pet = new Dog();
System.out.println("pet.sound(): " + pet.sound()); // Dog's version
System.out.println("greet(pet): " + greet(pet)); // Animal overload
System.out.println("greet((Dog) pet): " + greet((Dog) pet));
System.out.println("Animal.kind(): " + Animal.kind() + ", Dog.kind(): " + Dog.kind());
// Fields are not polymorphic either
Base b = new Derived();
System.out.println("field via Base reference: " + b.label);
System.out.println("field via Derived reference: " + ((Derived) b).label);
}
static class Base {
String label = "base";
}
static class Derived extends Base {
String label = "derived"; // a second, separate field that hides Base.label
}
}
Output:
pet.sound(): woof
greet(pet): greet(Animal)
greet((Dog) pet): greet(Dog)
Animal.kind(): animal, Dog.kind(): dog
field via Base reference: base
field via Derived reference: derived
printed "woof": overriding is resolved at run time from the object's class.pet.sound() chosegreet(pet) , even though the object is agreet(Animal) : overloading is resolved at compile time from the declared type of the argument. Casting toDog selected the other overload.Dog- Static methods and fields are not polymorphic.
hidesDog.kind() , and a field with the same name in a subclass is a second, separate field. Which one you get depends on the declared type, as the two field reads show. Avoid hiding: it is legal but misleading.Animal.kind()
| Overloading | Overriding | |
|---|---|---|
| Where | Same class (or a subclass) | A subclass |
| Signature | Different parameter types | Same name and parameter types |
| Chosen | At compile time, by declared argument types | At run time, by the object's class |
| Return type | Anything | Same, or a subtype (covariant) |
The order in which objects are built
Static and instance initialization of a parent and child class runs in a fixed order that matters whenever one part depends on another. The program logs every step: static fields and blocks, instance fields, an instance initializer block and constructors, for two objects in a row.
public class InitOrder {
static String log(String message) {
System.out.println(" " + message);
return message;
}
static class Parent {
static String s = log("1. Parent static field");
String f = log("Parent instance field");
static {
log("2. Parent static block");
}
Parent() {
log("Parent constructor body");
}
}
static class Child extends Parent {
static String s = log("3. Child static field");
String f = log("Child instance field");
static {
log("4. Child static block");
}
{
log("Child instance initializer block");
}
Child() {
super(); // runs the whole Parent part first
log("Child constructor body");
}
}
public static void main(String[] args) {
System.out.println("first new Child():");
new Child();
System.out.println("second new Child(): static parts do not run again");
new Child();
}
}
Output:
first new Child():
1. Parent static field
2. Parent static block
3. Child static field
4. Child static block
Parent instance field
Parent constructor body
Child instance field
Child instance initializer block
Child constructor body
second new Child(): static parts do not run again
Parent instance field
Parent constructor body
Child instance field
Child instance initializer block
Child constructor body
- Static parts run once, when each class is first used, parent before child, and in source order within each class (field, then block). The second
did not run them again.new Child() - For each object, the whole parent part (its instance fields, then its constructor body) is complete before the child's instance fields are even initialized.
- Within a class, instance field initializers and initializer blocks run in source order, before the constructor body.
- This order is why calling an overridable method from a parent constructor is dangerous: the child's fields are not yet set. The
abstract classes page shows that trap with real output.
Override rules and traps
An override must match the parent's method exactly, or it silently becomes something else. The program writes equals(Point)equals(Object)
import java.util.HashSet;
import java.util.Set;
public class OverrideTraps {
// Trap 1: equals(Point) OVERLOADS equals(Object) instead of overriding it
static final class Point {
final int x;
final int y;
Point(int x, int y) {
this.x = x;
this.y = y;
}
public boolean equals(Point other) { // no @Override, so no error
return other != null && x == other.x && y == other.y;
}
@Override
public int hashCode() {
return 31 * x + y;
}
}
// Covariant return type: an override may return a subtype
static class Shape {
Shape copy() {
return new Shape();
}
}
static class Circle extends Shape {
final double r;
Circle(double r) {
this.r = r;
}
@Override
Circle copy() { // returns Circle, not Shape
return new Circle(r);
}
}
public static void main(String[] args) {
Point a = new Point(1, 2);
Point b = new Point(1, 2);
Object asObject = b;
System.out.println("a.equals(b) with Point type: " + a.equals(b));
System.out.println("a.equals(b) with Object type: " + a.equals(asObject));
Set<Point> set = new HashSet<>();
set.add(a);
System.out.println("HashSet contains equal point: " + set.contains(b));
Circle c = new Circle(2.5);
Circle copy = c.copy(); // no cast needed
System.out.println("covariant copy radius: " + copy.r);
}
}
Output:
a.equals(b) with Point type: true
a.equals(b) with Object type: false
HashSet contains equal point: false
covariant copy radius: 2.5
does not overrideequals(Point) ; it is an overload. Called with aequals(Object) argument it worked, but called through anPoint reference, Java chose the inheritedObject , which compares identity, and returnedObject.equals .false callsHashSet , so it could not find an equal point.equals(Object)- Writing
on the method would have made this a compile error: "method does not override or implement a method from a supertype". Put@Override on every override; it costs nothing and catches typos and wrong parameter types.@Override returnsCircle.copy() whileCircle returnsShape.copy() . An override may narrow the return type (covariant return, Java 5), so callers holding aShape need no cast.Circle
| Rule | Detail |
|---|---|
| Same name and parameter types | Otherwise it is an overload |
| Return type | Same, or a subtype for reference types |
| Access | Same or wider; never narrower (see |
| Checked exceptions | Same, narrower or none; never new or broader ones |
| Not allowed for | finalstaticprivate |
When inheritance goes wrong
Two classic problems show the limits of inheritance. The first extends HashSetSquareRectangle
import java.util.Collection;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
public class FragileBaseClass {
// Inheritance: counts every element ever added... or tries to
static class CountingSet<E> extends HashSet<E> {
int added;
@Override
public boolean add(E e) {
added++;
return super.add(e);
}
@Override
public boolean addAll(Collection<? extends E> c) {
added += c.size();
return super.addAll(c); // HashSet.addAll calls add() for each element
}
}
// Composition: wraps a set instead of extending it
static class CountingSetWrapper<E> {
private final Set<E> inner = new HashSet<>();
int added;
boolean add(E e) {
added++;
return inner.add(e);
}
boolean addAll(Collection<? extends E> c) {
added += c.size();
return inner.addAll(c); // inner calls its own add, not ours
}
}
// Liskov substitution: a Square "is a" Rectangle mathematically, but not in code
static class Rectangle {
int width;
int height;
void setWidth(int w) {
width = w;
}
void setHeight(int h) {
height = h;
}
int area() {
return width * height;
}
}
static class Square extends Rectangle {
@Override
void setWidth(int w) {
width = w;
height = w;
}
@Override
void setHeight(int h) {
width = h;
height = h;
}
}
static int stretch(Rectangle r) { // written for rectangles
r.setWidth(5);
r.setHeight(4);
return r.area(); // a caller expects 20
}
public static void main(String[] args) {
CountingSet<String> inherited = new CountingSet<>();
inherited.addAll(List.of("a", "b", "c"));
System.out.println("extends HashSet: added 3 elements, counter says " + inherited.added);
CountingSetWrapper<String> wrapped = new CountingSetWrapper<>();
wrapped.addAll(List.of("a", "b", "c"));
System.out.println("wraps a HashSet: added 3 elements, counter says " + wrapped.added);
System.out.println("stretch(new Rectangle()) = " + stretch(new Rectangle()));
System.out.println("stretch(new Square()) = " + stretch(new Square()));
}
}
Output:
extends HashSet: added 3 elements, counter says 6
wraps a HashSet: added 3 elements, counter says 3
stretch(new Rectangle()) = 20
stretch(new Square()) = 16
- The counting subclass reported 6 additions for 3 elements. Its
added 3, then calledaddAll , which internally callsHashSet.addAll for each element, and thatadd is the overridden one, which counted again. The subclass depended on an implementation detail of its parent that is not part of the documented contract and could change in any release. This is the fragile base class problem.add - The wrapper version holds a
instead of being one, so the inner set's internal calls never reach the wrapper's methods, and it counted correctly. Preferring this composition over inheritance is the standard advice for classes you do not control.HashSet sets a width of 5 and a height of 4 and expects an area of 20. For astretch it got 16, because setting the height also changed the width. A subclass must work everywhere its parent works (the Liskov substitution principle); a mutable square cannot keep the promises of a mutable rectangle, even though mathematically every square is a rectangle.Square
Inheritance, interfaces or composition?
| Situation | Use |
|---|---|
| A genuine "is a" relationship within code you control, with shared state | Inheritance, often from an |
| Several unrelated types that share a capability | An |
| Adding behavior to a class you do not own | Composition: wrap it and delegate |
| Different behavior per type, chosen at run time | Overriding, or a strategy object or lambda passed in |
| A fixed set of subtypes handled in one place | A |
| Classes not designed for extension | Make them final |
Joshua Bloch's advice in Effective Java sums it up: design and document for inheritance, or else prohibit it.