ArchitectMind
  1. Home
  2. Java Ecosystem
  3. Book 1 · Core Java & Modern Java
  4. Volume I
  5. Inheritance
Book 1 · Volume I — Java Language Fundamentals & Object-Oriented Programming · Topic 6.1

Inheritance

extends, parent and child classes, single and multilevel inheritance

12 min readStage 1 · Foundations14 interview questions
Prerequisites
4.3 Constructors · 5.1 Encapsulation
Covers
extends · Parent class · Child class · Single inheritance · Multilevel inheritance
Related
6.2 Overriding · 6.4 Inheritance Design · 7.2 Multiple Interface Inheritance
On this page
  1. 1. Concept / Definition
  2. 2. Why It Exists
  3. 3. Core Concepts
  4. 4. How It Works Internally
  5. 5. APIs / Features / Syntax
  6. 6. Practical Examples
  7. 7. Common Problems & Mistakes
  8. 8. Performance & Production Considerations
  9. 9. Architecture & Design Considerations
  10. 10. Interview Questions & Answers
  11. Key Takeaways

1Concept / Definition

Inheritance lets a class — the child or subclass — be defined as an extension of another — the parent or superclass. The child automatically has the parent's accessible fields and methods, can add new members, and can override inherited methods. It also becomes a subtype: a child object can be used wherever the parent type is expected.

A hierarchy with single and multilevel inheritance
Figure 1 — A hierarchy with single and multilevel inheritance

2Why It Exists

Inheritance provides two things at once: code reuse (the subclass gets the superclass's implementation) and subtyping (the subclass can stand in for the superclass). The second is the more important. Much of the trouble with inheritance comes from using it only for the first, when composition would reuse code without creating a subtype relationship (6.4).

3Core Concepts

extends

class Manager extends Employee declares the relationship. A class names at most one superclass; if none is named, it implicitly extends java.lang.Object. A final class cannot be extended, and a sealed class can be extended only by the classes it permits.

Parent class

The parent defines shared state and behaviour and decides what subclasses may do: private members stay hidden, protected members form an API for subclasses, and final methods cannot be overridden. A parent class is a design commitment: once others extend it, its protected members and the way its methods call each other become part of its contract.

Child class

The child inherits accessible members, adds its own, and may override instance methods. It must initialise the parent part of the object by calling a parent constructor, explicitly with super(...) or implicitly with super() (4.3). Inside the child, super.method() calls the parent's version of an overridden method.

What a subclass receives from its superclass
Figure 2 — What a subclass receives from its superclass
A Manager object contains the fields declared by Employee as well as its own
Figure 3 — A Manager object contains the fields declared by Employee as well as its own

Single inheritance

A Java class has exactly one direct superclass. This avoids the "diamond problem" of multiple class inheritance, in which two parents provide conflicting state or implementations. Multiple inheritance of type is available through interfaces, which carry no instance state (7.2).

Multilevel inheritance

A hierarchy can be several levels deep: Object → Employee → Manager → Director. Each level inherits everything accessible above it. Depth has a cost: understanding Director requires reading every class above it, and each level adds coupling. Hierarchies deeper than two or three levels of application classes are a design warning sign.

4How It Works Internally

javac records the superclass in the class file, and the JVM builds each class from its parent. A subclass object contains every field declared by every class above it, the parent's first and then its own, whether they are private or not (Figure 3). The JVM also starts each class's method table from a copy of its parent's, replaces the entries of the methods the subclass overrides and appends its new ones (Figure 4). A normal call such as e.monthlyPay() compiles to invokevirtual, which looks up the entry in the table of the object's actual class. A super.monthlyPay() call compiles to invokespecial naming Employee.monthlyPay: it is bound at compile time and always runs the parent's code, as javap shows for Example 1:

TERMINAL
$ javap -c Manager
  public java.math.BigDecimal monthlyPay();
    Code:
       0: aload_0
       1: invokespecial #24 // Method Employee.monthlyPay:()Ljava/math/BigDecimal;
       ...                   // reports.size() * 500L, then BigDecimal.add
      24: areturn
Manager's method table: inherited entries, one replaced by the override, one new method
Figure 4 — Manager's method table: inherited entries, one replaced by the override, one new method

Because a super call names exactly one level up, there is no super.super.m(): a class can reach only its direct parent's implementation, which keeps each level responsible for calling the one above it. Constructors are not inherited at all. Each class's <init> begins by calling a constructor of its direct superclass (4.3), which is why construction always runs from Object downwards (Example 2).

5APIs / Features / Syntax

The keywords and forms that declare and control inheritance:

FormExampleMeaning
extendsclass Manager extends EmployeeOne direct superclass; java.lang.Object if none is named
super(...)super(name, baseSalary)Calls a parent constructor; the first call in the constructor (4.3)
super.m()super.monthlyPay()Runs the parent's implementation of an overridden method
protectedprotected final BigDecimal baseSalaryVisible to subclasses and to the package
finalfinal class Director / final void run()No subclass / no override
abstractabstract class ShapeCannot be instantiated; may declare abstract methods (5.2)
sealed, permits, non-sealed (Java 17)sealed class Account permits Savings, CurrentOnly the listed classes may extend it (Example 4)
instanceof, getClass()if (e instanceof Manager m)Tests the run-time class (6.3)

Every class also inherits the methods of Object, among them equals, hashCode, toString and getClass. 6.2 explains which of them to override, and how.

6Practical Examples

Example 1 — Employee and Manager

JAVAEmployee and Manager
public class Employee {
    private final String name;
    protected final BigDecimal baseSalary;          // API for subclasses

    public Employee(String name, BigDecimal baseSalary) {
        this.name = name;
        this.baseSalary = baseSalary;
    }
    public String name() { return name; }
    public BigDecimal monthlyPay() { return baseSalary; }
}

public class Manager extends Employee {
    private final List<Employee> reports = new ArrayList<>();

    public Manager(String name, BigDecimal baseSalary) {
        super(name, baseSalary);  // initialise the parent part
    }
    public void addReport(Employee e) { reports.add(e); }

    @Override
    public BigDecimal monthlyPay() {                 // specialise behaviour
        return super.monthlyPay().add(BigDecimal.valueOf(reports.size() * 500L));
    }
}

Employee e = new Manager("Ravi", new BigDecimal("90000"));   // subtype
System.out.println(e.monthlyPay());  // Manager's version

What to notice. The last line prints 90000: the variable has the type Employee, but the object is a Manager, so Manager.monthlyPay() runs, and with no reports it adds nothing to the base salary. baseSalary is protected, which lets Manager read it, but Manager still goes through super.monthlyPay(), so a later change to how Employee computes pay reaches managers too.

Example 2 — Mini program: a three-level hierarchy, traced

Problem. Section 3 describes multilevel inheritance; this program builds one, Employee > Manager > Director, and shows the three things that happen along the chain: constructors run from the top down, each override builds on the one above with super, and a list of Employee calls the right version for each object.

JAVAHierarchyTrace.java
public class HierarchyTrace {
    static class Employee {
        private final String name;
        protected final BigDecimal base;
        Employee(String name, String base) {
            this.name = name;
            this.base = new BigDecimal(base);
            System.out.println("  Employee(" + name + ")");
        }
        String name() { return name; }
        BigDecimal monthlyPay() { return base; }
        String title() { return "Employee"; }
    }
 
    static class Manager extends Employee {
        protected final List<Employee> reports = new ArrayList<>();
        Manager(String name, String base) {
            super(name, base);
            System.out.println("  Manager(" + name + ")");
        }
        void addReport(Employee e) { reports.add(e); }
        @Override BigDecimal monthlyPay() {          // + 500 per report
            return super.monthlyPay()
                        .add(BigDecimal.valueOf(500L * reports.size()));
        }
        @Override String title() { return "Manager"; }
    }
 
    static final class Director extends Manager {
        private final BigDecimal bonus;
        Director(String name, String base, String bonus) {
            super(name, base);
            this.bonus = new BigDecimal(bonus);
            System.out.println("  Director(" + name + ")");
        }
        @Override BigDecimal monthlyPay() {          // Manager's rule + bonus
            return super.monthlyPay().add(bonus);
        }
        @Override String title() { return "Director"; }
    }
 
    public static void main(String[] args) {
        System.out.println("creating a Director:");
        Director d = new Director("meera", "150000", "20000");
        Manager m = new Manager("ravi", "90000");
        Employee e = new Employee("asha", "60000");
        m.addReport(e);
        d.addReport(m);
        d.addReport(e);
        List<Employee> staff = List.of(e, m, d);     // all used as Employee
        for (Employee x : staff)
            System.out.println(x.title() + " " + x.name() + ": "
                    + x.monthlyPay());
    }
}
OUTPUT
creating a Director:
  Employee(meera)
  Manager(meera)
  Director(meera)
  Employee(ravi)
  Manager(ravi)
  Employee(asha)
Employee asha: 60000
Manager ravi: 90500
Director meera: 171000

Why it behaves this way. new Director(...) calls super(name, base), which calls Employee's constructor first, so the lines appear Employee, Manager, Director. The pay of the director is computed level by level: Director.monthlyPay() asks Manager.monthlyPay(), which adds 500 for each of the two reports to Employee's base, and then adds the bonus: 150,000 + 1,000 + 20,000 = 171,000. The loop declares x as Employee, yet title() and monthlyPay() run the most specific override for each object. Understanding Director required reading all three classes, which is the cost section 3 warns about.

Example 3 — Private fields are inherited as state, not as names

Problem. Q3 says that private members are part of the subclass object but not accessible in it. This program shows both halves, and what happens when a subclass declares a field with the same name as an inherited one.

JAVAPrivateState.java
public class PrivateState {
    static class Account {
        private long balance = 100;             // private: not inherited by name
        protected String id = "ACC";
        long balance() { return balance; }      // the subclass reaches it here
        void deposit(long amount) { balance += amount; }
    }
 
    static class SavingsAccount extends Account {
        protected String id = "SAV";            // hides Account.id: second field
        void addInterest() {
            // balance += 5;                         // does not compile: private
            deposit(balance() / 20);            // through the parent's methods
        }
        String ids() { return id + "/" + super.id; }
    }
 
    public static void main(String[] args) {
        SavingsAccount s = new SavingsAccount();
        s.addInterest();
        Account a = s;
        System.out.println("balance " + s.balance() + ", ids " + s.ids());
        System.out.println("a.id = " + a.id + ", s.id = " + s.id);
    }
}
OUTPUT
balance 105, ids SAV/ACC
a.id = ACC, s.id = SAV

Why it behaves this way. SavingsAccount cannot name balance, but the field exists in its objects, and the inherited methods balance() and deposit() work on it: 100 plus 5% interest gives 105. Declaring id again does not replace Account.id; the object now has two fields called id. Which one an expression reads depends on the declared type of the reference, SAV through SavingsAccount and ACC through Account, because fields are never dispatched dynamically (6.3). Keeping fields private avoids the confusion entirely.

Example 4 — A sealed hierarchy: inheritance with a closed list of subclasses

Problem. Section 9 recommends small sealed hierarchies for closed domain types. This program declares one: an account that only three classes may extend, one of which reopens its own branch with non-sealed.

JAVASealedAccounts.java
public class SealedAccounts {
    sealed abstract static class Account permits Savings, Current, Loan {
        private final long balance;
        Account(long balance) { this.balance = balance; }
        long balance() { return balance; }
    }
    static final class Savings extends Account {
        Savings(long b) { super(b); }
    }
    static final class Current extends Account {
        final long overdraft;
        Current(long b, long overdraft) { super(b); this.overdraft = overdraft; }
    }
    static non-sealed class Loan extends Account {   // open again below
        Loan(long b) { super(b); }
    }
    static class HomeLoan extends Loan {
        HomeLoan(long b) { super(b); }
    }
 
    static long available(Account a) {
        return switch (a) {                          // no default: the compiler
            case Savings s -> s.balance();           // knows every subclass
            case Current c -> c.balance() + c.overdraft;
            case Loan l -> 0;                        // HomeLoan matches here too
        };
    }
 
    public static void main(String[] args) {
        Account[] all = {new Savings(5_000), new Current(1_000, 20_000),
                         new Loan(-300_000), new HomeLoan(-2_500_000)};
        for (Account a : all)
            System.out.println(a.getClass().getSimpleName() + ": "
                    + available(a));
    }
}
OUTPUT
Savings: 5000
Current: 21000
Loan: 0
HomeLoan: 0

Why it behaves this way. permits lists every direct subclass, so the compiler knows the complete set, and the switch in available needs no default: if a fourth subclass were added, the switch would stop compiling until it was handled. Each permitted subclass must say how it continues: final closes it, and non-sealed opens Loan to further subclasses such as HomeLoan, which the case Loan branch also matches. Pattern matching in switch is final since Java 21; sealed classes since Java 17.

7Common Problems & Mistakes

MistakeWhy it hurtsWhat to do
Extending a class only to reuse a few of its methodsCreates a subtype nobody wanted: every inherited public method becomes part of your APIUse composition: hold the object and call it (6.4)
Deep hierarchiesOne class can be understood only by reading every class above it, and a change at the top ripples downKeep application hierarchies to two or three levels; move variation into collaborators
Protected fields shared across a hierarchyEvery subclass can break the parent's invariants, and the parent can never change its representationPrivate fields with protected methods where needed (5.1)
Extending classes not designed for it (JDK collections, third-party classes)Their internal self-calls are not part of the contract, so an upgrade can break the subclass (6.4)Wrap them instead of extending them (decorator)
Adding state in a subclass of a class with equalsequals is no longer symmetric or transitive: a base object equals a subclass object but not the reversePrefer composition, or make the base final; records cannot be extended
Redeclaring a parent's field in the subclassThe object has two fields, and which one is read depends on the reference type (Example 3)Keep fields private and never reuse a field name in a subclass

8Performance & Production Considerations

  • Inheritance itself is free at run time. Field access is a fixed offset and virtual calls are inlined by the JIT when a call site sees one or two classes (6.3); final is not needed for speed.
  • Subclassing framework and library classes is an upgrade risk. A subclass depends on the parent's implementation, so a minor version that changes how its methods call each other can break production code that still compiles. Prefer the interfaces and callbacks a framework publishes.
  • Object size grows with every level. Each level's fields are in every object, so a field added to a widely used base class costs memory in millions of instances.
  • Deep hierarchies slow incident work. When the behaviour of a call depends on overrides at several levels, a stack trace and a debugger are needed to see what actually ran; flat designs are faster to diagnose.

9Architecture & Design Considerations

In modern Java codebases inheritance of implementation is used sparingly: framework extension points (abstract base classes designed for extension), small sealed hierarchies for closed domain types, and occasionally a shared abstract base implementing an interface. Most variation is expressed with interfaces and composition. Frameworks such as Spring prefer interfaces and delegation for the same reasons.

10Interview Questions & Answers

Q1L1 · BasicConcept

What does extends do?

It makes the class a subclass of the named class: it inherits accessible members, can override instance methods, and becomes a subtype usable wherever the superclass is expected.

Q2L2 · IntermediateConcept

Why does Java not support multiple inheritance of classes?

To avoid ambiguity and complexity when two superclasses provide conflicting state or method implementations (the diamond problem). Java allows multiple inheritance of type through interfaces, which have no instance state, with explicit rules for conflicting default methods.

Q3L2 · IntermediateTricky

Are private members inherited?

They are part of the subclass object — the memory exists and superclass methods use it — but they are not accessible by name in the subclass, so they are not inherited in the language sense. Example 3 shows it.

Q4L3 · Senior EngineerInternals

What happens if a superclass has no no-argument constructor?

Every subclass constructor must explicitly call a superclass constructor with super(...) and suitable arguments; otherwise compilation fails, because the implicit super() has nothing to call.

Q5L3 · Senior EngineerTrade-off

Why are deep inheritance hierarchies a problem?

Behaviour is spread across many classes, changes in upper levels ripple down unpredictably, and understanding or testing one class requires understanding all of its ancestors. They also lock in one classification of the domain that is often wrong later.

Q6L4 · Technical ArchitectDesign

Where is class inheritance still the right choice in modern Java?

For small, closed families of types — ideally sealed — that genuinely share behaviour and satisfy LSP; for framework extension points explicitly designed and documented for subclassing; and for abstract base classes that implement an interface to share common code. Elsewhere, interfaces and composition are usually better.

Q7L1 · BasicConcept

What does every Java class inherit from Object?

The methods equals, hashCode, toString, getClass, clone (protected), finalize (deprecated) and the monitor methods wait, notify and notifyAll. getClass and the monitor methods are final; equals, hashCode and toString are the ones classes commonly override, and the first two must be overridden together (4.2, 6.2).

Q8L2 · IntermediateConcept

What is the difference between extends and implements?

A class extends one class and inherits its state and implementation, and it implements any number of interfaces, which contribute a type and, through default methods, possibly behaviour but no instance state. An interface extends other interfaces. Choose extends only for a real subtype of a class designed for it; implements is the usual way to make a class usable as several types.

Q9L2 · IntermediateCode

What does this program print?

JAVAInheritQuiz.java
public class InheritQuiz {
    static class A {
        A() { System.out.print("A "); }
        String who() { return "A"; }
        String call() { return who(); }
    }
    static class B extends A {
        B() { System.out.print("B "); }
        @Override String who() { return "B+" + super.who(); }
    }
    static class C extends B {
        C() { super(); System.out.print("C "); }
    }
 
    public static void main(String[] args) {
        A x = new C();
        System.out.println("| " + x.call());
    }
}

It prints A B C | B+A. Creating a C runs the constructors from the top down: A, then B, then C. call() is declared in A, but its call to who() is dispatched on the object, a C, which inherits B's override; that override returns "B+" followed by super.who(), which is A's version. Code in a superclass therefore runs subclass behaviour whenever it calls an overridable method.

Q10L3 · Senior EngineerInternals

How is super.method() compiled, and why is there no super.super.method()?

javac compiles super.monthlyPay() to invokespecial with the direct superclass's method as the target, so it is bound at compile time and skips the virtual lookup that would select the current override (section 4). The language allows only the direct parent as the target, so that each class decides whether and how its own parent's code runs; reaching past it would let a subclass bypass behaviour that the intermediate class deliberately added or changed.

Q11L3 · Senior EngineerTricky

A subclass declares a private method with the same name and parameters as a private method of its parent. Does it override it?

No. Private methods are not inherited, so the subclass method is a new, unrelated method. Code in the parent that calls its private method always runs the parent's version, even on a subclass object, and @Override on the subclass method would be a compile error, which is exactly how the annotation catches the mistake. The same applies to static methods, which are hidden rather than overridden (6.2).

Q12L3 · Senior EngineerScenario

After a minor upgrade of a library, a class that extends one of its base classes starts producing wrong totals, although nothing in your code changed and everything compiles. What do you suspect?

The fragile base class problem: the subclass depended on how the base class's methods call each other, and the new version changed that, so an override now runs twice, or no longer runs at all. Compare the two library versions for changes in the overridden methods and their callers, and write a test that fails with the new one. The lasting fix is to stop extending a class that was not designed for it: wrap it and forward calls, or use the extension interface the library documents (6.4).

Q13L4 · Technical ArchitectTrade-off

Several classes share 200 lines of code. Would you put it in an abstract base class or in a helper the classes delegate to?

An abstract base class is right when the classes are genuine subtypes of one concept, share state as well as code, and the shared part is a fixed algorithm with steps that vary (Template Method). It costs the single superclass slot and couples every subclass to the base's implementation. Delegating to a helper object keeps the classes free to extend something else, lets the helper be tested and replaced separately, and exposes nothing extra. When in doubt, choose delegation; keep the base class behind an interface so that callers never depend on it.

Q14L5 · Solution ArchitectScenario

Two teams extend the same BaseEntity class from a shared library, and each change one team needs breaks the other. How do you restructure this?

The base class has become a shared implementation that both teams depend on in different ways. Freeze it and move its responsibilities into small, separate pieces: interfaces for the roles, such as identity or auditing, and helper components that entities use by composition. Let each team adopt them at its own pace, with the old base class deprecated and kept stable until both have moved. Add an architecture rule that forbids new subclasses of library classes not marked as extension points, so the coupling does not return.

Test your knowledge on this topic →Flashcards from this topic's 14 questions, filtered by level and type.

Key Takeaways

  • extends gives code reuse and subtyping; subtyping is what matters.
  • One direct superclass; interfaces provide multiple inheritance of type.
  • Constructors are not inherited; the parent part is initialised with super(...).
  • Keep hierarchies shallow; extend only classes designed for it.
Free question pack

Get 100 free Core Java interview questions

Subscribe for the Book 1 question pack (PDF, every answer explained) and new tutorials once a week. No spam, unsubscribe anytime. What is in the pack?

Almost done! Check your inbox and click the confirmation link. Your download link arrives as soon as you confirm.