Java Inheritance Design Hints: Best Practices for Class Hierarchies
Seven practical rules for Java class hierarchies: put common code in superclasses, avoid protected fields, inherit only for true is-a relationships, keep inherited methods meaningful, honor the substitution principle, prefer polymorphism over type tests, and use reflection sparingly.
kvi5hnuCode Sprout team member9 min readOn this page
Part 5 covered the inheritance toolbox: subclasses and super, polymorphism, final and protected, Object's methods, abstract classes, enums, sealed types, pattern matching and reflection. Tools can be misused, and inheritance is the one most often misused in object-oriented code. Below are seven guidelines for hierarchies that stay easy to change, each with the reasoning behind it.

1. Move Shared State and Behavior Up
When sibling classes repeat the same field or method, move it into their common superclass and write it once. In the abstract classes article, title and getTitle() live in MediaItem, not separately in Book and Podcast. Copies don't stay identical: sooner or later one gets fixed and the other doesn't.
The guideline has a limit. Moving something up means every subclass gets it. If only some subclasses need a method, putting it in the superclass forces it onto classes where it is meaningless (guideline 4).
2. Keep Fields Out of protected
Marking fields protected so that subclasses "might need them" exposes more than it seems, because the protected rules are generous:
- Anyone can write a subclass. Every subclass, including ones you'll never see, may read and write a protected field directly. From then on, renaming or restructuring that field breaks code you don't control.
- The whole package has access. Java's
protectedincludes package access, so even non-subclasses in the same package can touch the field.
Keep fields private and offer subclasses methods instead. protected methods are a different matter: they are a deliberate extension point for subclasses, like the hook methods of the template method pattern.
3. Inherit Only When "Is-A" Is True
Inheritance hands you existing code for free, which makes it tempting to use where it doesn't belong. Consider adding contractors to the staff system. A contractor has a name and a start date, but is paid by the hour and never receives a salary raise. Extending Employee looks like a shortcut:
public class Contractor extends Employee { // don't
private double hourlyWage;
. . .
}
Now each contractor carries an unused salary, giveRaise is callable on contractors, and payroll code fills up with if (x instanceof Contractor) exceptions. The shortcut ends up costing more code than it saved.
Ask the is-a question honestly: is a contractor a kind of employee in this system? No. What the two share is being a worker with a name, a start date and some way of computing pay. Make that the superclass and let both classes extend it, as the diagram shows.
4. Every Inherited Method Must Make Sense
A subclass takes all public methods of its superclass, not just the ones you had in mind. Imagine a list of exam scores that must always stay sorted:
class SortedScores extends ArrayList<Integer> { // don't
@Override public boolean add(Integer s) { . . . } // inserts at the right position
}
Overriding add doesn't make the class safe, because ArrayList also offers set(int, E), add(int, E), addAll, replaceAll, sort with any comparator, and more. Each of them can break the "always sorted" guarantee:
SortedScores s = . . .;
s.set(0, 999); // the smallest position now holds the largest value
The type promises something that its inherited methods can't keep, so inheritance is the wrong tool. Wrap a private list instead and expose only operations that preserve the order. The same reasoning explains why the Holiday in the program below holds a LocalDate rather than extending a date class: shifting a holiday by twelve days must not produce something that still claims to be that holiday.
5. Overrides Must Keep the Superclass's Promises
The substitution principle is about behavior, not just matching signatures. Callers written against the superclass rely on what its methods do, and the compiler can't verify that an override still does it.
Suppose someone "fixes" SortedScores by overriding set to ignore the call, or to throw. Code written for any List expects this to hold:
list.set(0, 42);
System.out.println(list.get(0)); // a List promises 42 here
A silently ignored set breaks that expectation, and a thrown exception surprises every caller that was written for lists in general. Either way the subclass can't be substituted for its superclass.
What counts as "expected" can be debated; the equals discussion in the equals and inheritance article is one example. The practical rule: honor the documented intent of the method you override, and when you design a superclass, write that intent down in its Javadoc ("increases the count by exactly one"). This is the Liskov substitution principle, the "L" in SOLID.
6. Prefer Polymorphism to Type Checks
A chain like
if (x is of type 1)
action1(x);
else if (x is of type 2)
action2(x);
usually means a method is missing. If action1 and action2 are two versions of one idea, declare that idea as a method of the common supertype and let each class implement its version:
x.action();
Dynamic dispatch then picks the right code, and a new subclass brings its own implementation without anyone editing the chain. In the program below, monthlyPay() plays this role: the loop treats salaried staff and contractors alike.
Modern Java adds one nuance. For a closed set of types, a sealed hierarchy with a pattern-matching switch is a sound choice, because the compiler checks that every type is handled. Rule of thumb: when new types keep arriving, use polymorphism; when the types are fixed and new operations keep arriving, use a sealed type and switches. Avoid if/instanceof chains over open hierarchies, where nothing tells you about a forgotten case.
7. Keep Reflection for Tools
Reflection makes extremely general code possible, which is why frameworks, serializers, test runners and IDEs are built on it. In application code it is usually the wrong choice: errors that the compiler would catch turn into runtime exceptions, encapsulation is bypassed, calls are slower, and the module system increasingly blocks deep access (see analyzing objects with reflection). Interfaces, lambdas and method references cover nearly all everyday needs.
The Hints in Code
import java.time.LocalDate;
import java.time.Month;
import java.util.List;
import java.util.Locale;
public class Solution {
public static void main(String[] args) {
// Hint 1 and 6: common code in the superclass, polymorphism instead of type tests
List<Worker> staff = List.of(
new SalariedEmployee("Omar Haddad", LocalDate.of(2019, 9, 2), 52000),
new Contractor("Priya Nair", LocalDate.of(2025, 3, 15), 85.0, 120));
for (Worker w : staff) {
System.out.printf(Locale.US, "%-13s hired %s pay this month: $%,10.2f%n",
w.getName(), w.getStartDate(), w.monthlyPay());
}
// Hint 4: a Holiday that can't be turned into a non-holiday (composition + immutable date)
Holiday christmas = Holiday.of("Christmas", LocalDate.of(2026, Month.DECEMBER, 25));
LocalDate later = christmas.date().plusDays(12); // a new LocalDate, not a Holiday
System.out.println(christmas + " -> 12 days later is " + later + " (just a date)");
// Hint 5: an override that keeps the contract
Counter c = new LoggingCounter();
c.increment();
c.increment();
System.out.println("count = " + c.get());
}
}
/** Hint 1: common fields and operations live in the superclass. */
abstract class Worker {
private final String name; // Hint 2: private, not protected
private final LocalDate startDate;
protected Worker(String name, LocalDate startDate) {
this.name = name;
this.startDate = startDate;
}
public String getName() { return name; }
public LocalDate getStartDate() { return startDate; }
/** Hint 6: every kind of worker computes its own pay. */
public abstract double monthlyPay();
}
/** Hint 3: a salaried employee is-a worker. */
class SalariedEmployee extends Worker {
private double salary;
SalariedEmployee(String name, LocalDate startDate, double salary) {
super(name, startDate);
this.salary = salary;
}
public void giveRaise(double pct) { salary += salary * pct / 100; }
@Override public double monthlyPay() { return salary / 12; }
}
/** A contractor is not a special employee: no salary field, no raises. */
class Contractor extends Worker {
private final double hourlyWage;
private final int hoursThisMonth;
Contractor(String name, LocalDate startDate, double hourlyWage, int hoursThisMonth) {
super(name, startDate);
this.hourlyWage = hourlyWage;
this.hoursThisMonth = hoursThisMonth;
}
@Override public double monthlyPay() { return hourlyWage * hoursThisMonth; }
}
/** Hint 4: has-a date instead of is-a mutable calendar. */
record Holiday(String name, LocalDate date) {
static Holiday of(String name, LocalDate date) { return new Holiday(name, date); }
}
/** Hint 5: subclasses may add behavior but must keep the documented contract. */
class Counter {
private int count;
/** Increases the count by exactly one. */
public void increment() { count++; }
public int get() { return count; }
}
class LoggingCounter extends Counter {
@Override public void increment() {
super.increment(); // keeps "exactly one"
System.out.println("increment -> " + get());
}
}
Omar Haddad hired 2019-09-02 pay this month: $ 4,333.33
Priya Nair hired 2025-03-15 pay this month: $ 10,200.00
Holiday[name=Christmas, date=2026-12-25] -> 12 days later is 2027-01-06 (just a date)
increment -> 1
increment -> 2
count = 2
Workerholds the common fields and declares the common operation (guidelines 1 and 6), withprivatefields (guideline 2).ContractorandSalariedEmployeeare both workers, but a contractor isn't an employee (guideline 3).Holidayhas a date. Adding twelve days produces a plainLocalDate, never a bogus holiday (guideline 4).LoggingCounteradds logging but keeps the "exactly one" contract ofincrement(guideline 5).
Common questions
How do I know whether a class is designed for inheritance?
Look at its documentation. A class designed for extension documents which methods subclasses may override and how its methods call each other ("This implementation calls add..."). If there's no such documentation and the class isn't abstract, prefer composition. Modern libraries often make classes final or sealed to make this explicit.
Is inheritance ever better than composition?
Yes, when there's a genuine "is-a" relationship and the subclass honours every inherited method's contract, as with Manager and Employee, or a skeletal implementation such as AbstractList. It is also needed by frameworks that require a base class. Use composition when you only want to reuse code.
What is the Liskov Substitution Principle in one sentence? Code written for a superclass must keep working correctly when handed any subclass object. That means subclasses can't strengthen preconditions, weaken guarantees or throw surprising exceptions in overridden methods.
When is an instanceof chain acceptable?
At system boundaries where you receive values of unknown type (for example equals(Object), or deserialised data), and in exhaustive pattern switches over sealed types. Within your own open hierarchies, add a polymorphic method instead.
Should I make every class final by default?
Many teams do for application code, because it keeps options open and prevents accidental fragile subclasses. Remove final deliberately when you design a class for extension. Library authors in particular benefit from final and sealed, because every extensible class is an API commitment.
Summary of Part 5
| Guideline | In one line |
|---|---|
| 1 | Put shared fields and methods in the superclass |
| 2 | Keep fields private; protected is for methods meant for subclasses |
| 3 | Inherit only for true is-a relationships; otherwise use composition |
| 4 | Every inherited method must make sense for the subclass |
| 5 | Overrides must honor the superclass contract (Liskov) |
| 6 | Replace type tests with polymorphism, or with exhaustive switches over sealed types |
| 7 | Reflection is for tools and frameworks, not everyday code |
With classes, inheritance and polymorphism in place, Part 6 turns to interfaces and lambda expressions, the tools modern Java uses most for flexible, decoupled code.
Practice Questions
A Square class extends Rectangle and overrides setWidth to also set the height. Which hint does this violate, and why?
Hint 5, the substitution principle. Code that works with a Rectangle expects setWidth to leave the height unchanged; for example, after setWidth(5); setHeight(4) it expects an area of 20. A Square breaks that expectation. Better designs make shapes immutable or don't relate Square and Rectangle by inheritance.
Why is a protected field less protected than it looks?
Any class anywhere can subclass yours and access it, and every class in the same package can access it even without subclassing. So it's effectively part of your public API.
You want a Stack class with push and pop. Should it extend ArrayList?
No. A stack isn't a list: inheriting add(int, E), remove(int) and set would let callers break the stack discipline (hint 4). Use composition: a private ArrayList or ArrayDeque field with only push, pop and peek exposed. (The JDK's own java.util.Stack extends Vector is a well-known example of this mistake.)
Rewrite this using polymorphism: if (s instanceof Circle c) area = PIc.r; else if (s instanceof Square q) area = q.side*q.side;
Declare double area() in a common Shape interface or superclass, implement it in Circle and Square, and call s.area(). If Shape is sealed, an exhaustive pattern-matching switch is also acceptable.
When is reflection the right tool?
When writing infrastructure that must work with classes unknown at compile time: serialization, dependency injection, ORMs, test frameworks, debuggers, plugin loading. Not for ordinary application logic, where interfaces and lambdas are safer and faster.
Previous: Java Reflection: Invoking Methods and Writing Generic Array Code
Next: Java Interfaces: Declaring and Implementing Interfaces
Related reading
- Java Reflection: Analyzing Classes and Inspecting Objects at Runtime
- Java Reflection: The Class Class, Exceptions Primer and Loading Resources
- Java Sealed Classes and Interfaces: Controlling Inheritance
- Java Enum Classes: Enumerated Types with Fields and Methods
- Java Abstract Classes and Abstract Methods

More in Core Java I
Java volatile, Atomics, Deadlocks and ThreadLocal: Safe Sharing Between Threads
Share data between Java threads without bugs: memory visibility and volatile, final fields, AtomicInteger and compareAndSet, LongAdder, lazy holder initialization, safe publication, lock-ordering deadlocks, ThreadLocal, InheritableThreadLocal and ScopedValue.
Java Condition Objects and the synchronized Keyword: await, signalAll, wait and notify
Make threads wait for a condition safely with Condition.await and signalAll, then learn Java's built-in alternative: synchronized methods and blocks, intrinsic locks, wait and notifyAll, choosing lock objects, client-side locking, and the monitor concept.
Java Race Conditions and ReentrantLock: Synchronizing Shared Data
Why unsynchronized threads corrupt shared data, shown step by step with a lost-update race, and how to fix it with ReentrantLock: the lock/try/finally idiom, critical sections, reentrancy and hold counts, tryLock, fair locks, and the mistakes that cause bugs.
Java invokeAll, invokeAny and Fork-Join: Running Groups of Tasks
Coordinate many concurrent tasks in Java: invokeAll to wait for every result, invokeAny to take the first success, timeouts, ExecutorCompletionService for results in completion order, structured concurrency, and the fork-join framework with RecursiveTask, RecursiveAction and work stealing.
Discussion
Sign in to ask a question or share what you learned.