Java Inheritance: Superclasses, Subclasses and Method Overriding
Learn Java inheritance step by step: defining subclasses with extends, what a subclass inherits, overriding methods and calling super.method(), the @Override annotation, subclass constructors with super(...), inheritance hierarchies, and why Java has no multiple inheritance of classes.
kvi5hnuCode Sprout team member11 min readOn this page
Part 4 was about single classes. Part 5 is about relationships between classes, starting with inheritance: declaring a new class as an extension of an existing one. The new class automatically gets the old class's fields and methods, and then adds its own or replaces the ones that don't fit. Inheritance runs through the whole JDK; the exception classes, the collections and the I/O streams are all organized as hierarchies.
Later in this part you'll also meet Object (the superclass of every class), array lists, wrapper classes, enums, sealed classes, pattern matching and reflection, the ability to inspect classes at runtime.
Defining Subclasses
Take the Employee class from Part 4 and add a new requirement: managers earn a salary like everyone else, plus a bonus on top.
Copying Employee into a new Manager class and editing it would duplicate every field and method. Instead, Manager can declare that it is an Employee with one extra piece of data. That "is-a" test is how you recognize a good use of inheritance: any manager can be used wherever an employee is expected.
Use the keyword extends:
public class Manager extends Employee {
// added fields and methods
}
extends means you're making a new class that derives from an existing one:
Existing class (Employee) | New class (Manager) |
|---|---|
| superclass | subclass |
| base class | derived class |
| parent class | child class |
Java programmers most often say superclass and subclass.
Manager adds one field and a method that sets it:
public class Manager extends Employee {
private double bonus;
. . .
public void setBonus(double bonus) {
this.bonus = bonus;
}
}
setBonus is an ordinary method, called on a Manager like any other:
Manager boss = . . .;
boss.setBonus(6500);
The reverse doesn't work: an Employee has no setBonus. A Manager, on the other hand, can do everything an Employee can. getName() and getStartDate() work on it although Manager never declares them; they are inherited.
The same goes for data. A Manager object carries four fields: the three declared in Employee (name, salary, startDate) and its own bonus.

A subclass declaration lists only what is different. Shared behavior belongs as high in the hierarchy as it makes sense, special cases lower down. When two classes turn out to share code, moving that code up into a common superclass is a routine refactoring.
Overriding Methods
An inherited method may be wrong for the subclass. For a manager, getSalary() must include the bonus. So Manager declares its own getSalary(), which overrides (replaces) the inherited one:
public class Manager extends Employee {
. . .
public double getSalary() {
. . .
}
}
Two mistakes are common when writing it. Reading the field directly doesn't compile, because salary is private to Employee:
return salary + bonus; // error: salary has private access in Employee
Calling getSalary() compiles, but inside Manager that name now means the method being written, so it calls itself until the stack runs out:
return getSalary() + bonus; // StackOverflowError at run time
What you want is "the version of this method that Employee provides". That is what the keyword super selects:
public double getSalary() {
double baseSalary = super.getSalary(); // calls Employee.getSalary
return baseSalary + bonus;
}
A subclass can add fields, add methods, and override methods. But inheritance can never take away a field or method. A Manager always has everything an Employee has.
Always use @Override
Put the @Override annotation on every method that's meant to override:
@Override
public double getSalary() {
return super.getSalary() + bonus;
}
If the method doesn't actually override anything, because of a typo or a wrong parameter type, the compiler reports an error instead of silently creating a new method:
@Override
public double getSallary() { . . . } // error: method does not override or implement a method from a supertype
Without @Override, getSallary would compile as a brand-new method, and managers would quietly lose their bonus. IDEs insert @Override automatically when you generate overriding methods. Use it every time.
The rules for a legal override (same signature, compatible return type, no weaker access) are covered in the next article on polymorphism and dynamic binding.
Subclass Constructors
To complete the example, add a constructor:
public Manager(String name, double salary, int year, int month, int day) {
super(name, salary, year, month, day);
bonus = 0;
}
Here super has a different meaning. The statement
super(name, salary, year, month, day);
is shorthand for "call the constructor of the Employee superclass with these arguments".
Manager's constructor can't access Employee's private fields, so it must initialize them through a superclass constructor, invoked with the super(...) syntax. The super(...) call comes before any use of this in the constructor, and traditionally it had to be the first statement.
If a subclass constructor doesn't call a superclass constructor explicitly, the compiler inserts super(), a call to the superclass's no-argument constructor. If the superclass has no such constructor, that's a compile error:
class NoArg extends Employee {
NoArg() { } // error: constructor Employee in class Employee cannot be applied to given types
}
The same happens when the subclass has no constructor at all: its default constructor calls super().
Java 25: statements before super(...)
Before Java 25, super(...) had to be literally the first statement, which made it awkward to validate or prepare arguments before passing them up. Java 25 finalized flexible constructor bodies (JEP 513). Statements may now come before super(...) or this(...), as long as they don't use the object under construction (no reading of this's fields, no instance method calls):
public Manager(String name, double salary, int year, int month, int day) {
if (salary < 0) {
throw new IllegalArgumentException("Negative salary: " + salary); // validate first (Java 25+)
}
super(name, salary, year, month, day);
bonus = 0;
}
Such a "prologue" may also assign the subclass's own fields before calling super(...). This ensures that they're initialized even if the superclass constructor calls an overridden method. On Java 21, validate in a static helper instead: super(name, requireNonNegative(salary), year, month, day);.
Putting It Together
The program below creates one manager with a bonus and two ordinary employees, stores all three in an Employee[], and prints everyone's salary:
import java.time.LocalDate;
public class Solution {
public static void main(String[] args) {
var boss = new Manager("Priya Nair", 91000, 2016, 4, 11);
boss.setBonus(6500);
Employee[] staff = {
boss, // a Manager stored as an Employee
new Employee("Omar Haddad", 52000, 2019, 9, 2),
new Employee("Lena Fischer", 46000, 2021, 6, 21)
};
for (Employee e : staff) {
System.out.println("name=" + e.getName() + ",salary=" + e.getSalary());
}
System.out.println(boss.getStartDate()); // inherited method
}
}
class Employee {
private String name;
private double salary;
private LocalDate startDate;
public Employee(String name, double salary, int year, int month, int day) {
this.name = name;
this.salary = salary;
startDate = LocalDate.of(year, month, day);
}
public String getName() { return name; }
public double getSalary() { return salary; }
public LocalDate getStartDate() { return startDate; }
public void giveRaise(double pct) {
double raise = salary * pct / 100;
salary += raise;
}
}
class Manager extends Employee {
private double bonus;
public Manager(String name, double salary, int year, int month, int day) {
super(name, salary, year, month, day);
bonus = 0;
}
@Override
public double getSalary() {
double baseSalary = super.getSalary();
return baseSalary + bonus;
}
public void setBonus(double bonus) {
this.bonus = bonus;
}
}
name=Priya Nair,salary=97500.0
name=Omar Haddad,salary=52000.0
name=Lena Fischer,salary=46000.0
2016-04-11
Omar and Lena are plain Employee objects, so they print their base salary. Priya's object is a Manager, and her line includes the 6500 bonus.
Look at the loop again: there is only one call, e.getSalary(), and e is declared as Employee. Yet for Priya the Manager version runs. The compiler only knows the declared type; at run time the JVM checks the actual class of the object and runs that class's method.
- That a variable like
ecan refer to objects of multiple actual types is called polymorphism. - Automatically selecting the right method at runtime is called dynamic binding.
Both are explored in the next article.
Inheritance Hierarchies
A subclass can itself be extended: a Director class could extend Manager. A class together with everything below it forms an inheritance hierarchy, and the sequence of superclasses from one class up to the top is its inheritance chain.

Hierarchies branch. Engineer and Accountant might both extend Employee directly, sharing nothing with Manager or with each other except what Employee provides. The hierarchy can grow as deep and wide as needed. At the very top is Object, the implicit superclass of every class that doesn't name one; it's covered later in this part.
Common questions
Does a subclass inherit constructors?
No. Constructors are never inherited. Every subclass needs its own constructors (or the default one), and each of them calls a superclass constructor, explicitly with super(...) or implicitly with super().
Can I call a grandparent's method, like super.super.getSalary()?
No. super reaches only the direct superclass's version of a method. If the direct superclass doesn't override the method, super.m() automatically finds the grandparent's version. Wanting to skip a level usually means the hierarchy needs redesigning.
Is @Override required?
The compiler doesn't require it, but you should always write it. It turns a misspelled or mistyped override into a compile error instead of a silent new method. It also documents intent for readers. IDEs and static analysis tools flag missing @Override annotations.
Should I use inheritance just to reuse code? Usually not. Inheritance is for genuine "is-a" relationships where the subclass honours the superclass's contract. For reusing code, composition (holding a helper object and delegating to it) is more flexible and doesn't expose your class to changes in a superclass you don't control.
Can a subclass make an inherited method less visible?
No. An overriding method must be at least as accessible as the method it overrides. A public method stays public in every subclass. This guarantees that code written for the superclass can call the method on any subclass object.
Summary
class Sub extends Supercreates a subclass that inherits the superclass's fields and methods and can add new ones.- Subclass objects contain the superclass's private fields, but subclass code must use the superclass's methods to reach them.
- A subclass overrides a method by declaring one with the same signature. Inside it,
super.method()calls the superclass version. Callingmethod()would recurse. - Annotate overriding methods with
@Overrideso the compiler catches mistakes. - Subclass constructors initialize the superclass part with
super(...). Without an explicit call,super()(the no-argument constructor) is called implicitly. Java 25 allows validation statements beforesuper(...). - Inheritance hierarchies can be deep and wide, but every class has exactly one direct superclass.
Practice Questions
Why does return salary + bonus; fail to compile in Manager.getSalary, even though a Manager object contains a salary field?
salary is private in Employee, so only Employee's own methods can access it. Manager must use the public interface: super.getSalary() + bonus.
What happens if Manager.getSalary() is written as return getSalary() + bonus;?
It calls itself recursively (dynamic binding selects Manager.getSalary), endlessly, until the stack overflows: java.lang.StackOverflowError. Use super.getSalary().
Employee has only the constructor Employee(String name). Does class Intern extends Employee { } compile?
No. Intern gets a default constructor that calls super(), but Employee has no no-argument constructor. Add a constructor such as Intern(String name) { super(name); }.
What does @Override buy you if your method already overrides correctly?
Nothing at runtime, but it documents intent and protects you against future mistakes. If someone renames or changes the superclass method's parameters, the compiler reports an error instead of letting your method silently stop overriding.
A Student and an Employee class both exist. How would you model a TeachingAssistant who is both?
Java doesn't allow extends Student, Employee. Options: extend one class and implement interfaces for the other role (e.g., class TeachingAssistant extends Student implements Payable), or use composition (a TeachingAssistant that has a Student record and an Employment object).
Previous: Java Class Design Hints: Writing Clean, Maintainable Classes
Next: Java Polymorphism and Dynamic Binding: How Method Calls Are Resolved
Related reading
- Java Class Design Hints: Writing Clean, Maintainable Classes
- Java Package Access and the Class Path
- Java Records: Compact Data Classes with Canonical and Compact Constructors
- Java static Fields and Methods: Class Variables, Constants, Factory Methods and main
- Defining Your Own Classes in Java: Fields, Constructors and 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.