skip to content

Inheritance (Mechanics)

Java's inheritance mechanics: extending a class, overriding versus hiding, and using final to close a type down. This area is where most subtle dispatch questions come from.

part ofJavaoverview, primer and where to startread it →
on this pageshow

explore

questions

19

What does the extends keyword do in Java, and what does it mean that Java only allows single class inheritance?

level: juniorimportance: must knowfreq 85%

answer

  1. extends = one direct parent
  2. single class inheritance → no diamond
  3. interfaces give multiple behavior
  4. no extends → implicitly extends Object
  5. is-a relationship enables polymorphism

basics

~10 s

extends makes one class a subclass of another, so the subclass inherits the parent's fields and methods. Java allows a class to extend only one direct parent class (single inheritance).

solid answer

~40 s

The extends keyword declares a class as a subclass of exactly one superclass: 'class Dog extends Animal'. The subclass inherits all accessible (non-private) fields and methods and can add its own or override inherited ones. Java enforces single class inheritance: a class can have only one direct superclass, which avoids the diamond ambiguity that multiple class inheritance creates. To get behavior from multiple sources you implement multiple interfaces (which can carry default methods) rather than extending multiple classes. Every class without an explicit extends clause implicitly extends Object, so the inheritance graph is always a single rooted tree. Inheritance models an 'is-a' relationship and enables polymorphism: a reference of the superclass type can hold any subclass instance.

code

java · 14 lines
java
class Animal {
    void breathe() { System.out.println("breathing"); }
}

class Dog extends Animal {        // single parent
    void bark() { System.out.println("woof"); }
}

// class Dog extends Animal, Pet  // COMPILE ERROR: no multiple class inheritance

Dog d = new Dog();
d.breathe();   // inherited from Animal
d.bark();      // declared in Dog
Animal a = d;  // polymorphism: Dog is-a Animal

go deeper

for a junior

Knows extends creates a subclass, that only one parent class is allowed, and that the subclass gets the parent's accessible members.

for a middle

Explains why single inheritance exists (diamond problem), contrasts extends vs implements, and knows every class extends Object implicitly.

for a senior

Discusses inheritance vs composition trade-offs, default-method conflict resolution across interfaces, and how polymorphism follows from is-a.

for a principal

Frames inheritance as a coupling decision in API/architecture design, weighs fragile-base-class risks, and guides teams toward composition or sealed hierarchies where appropriate.

## What 'inheritance' means **Inheritance** is a mechanism where one class (the **subclass** or **child**) is defined in terms of another (the **superclass** or **parent**), automatically acquiring the parent's members. A **member** is a field (variable) or method (function) declared in a class. The point is reuse and modeling an **is-a** relationship: a `Dog` *is an* `Animal`. ## The `extends` keyword In Java you create this relationship with `extends`: ```java class Animal { void breathe() {} } class Dog extends Animal { void bark() {} } ``` Here `Dog` is a subclass of `Animal`. A `Dog` object now has both `bark()` (its own) and `breathe()` (inherited). The subclass inherits every member that is **accessible** to it — that means everything except `private` members (private members exist in the parent object but cannot be referenced by name from the subclass). ## Single (class) inheritance Java allows a class to list **only one** class after `extends`. This is **single inheritance**. You cannot write `class C extends A, B`. The reason is the **diamond problem**: if a class could inherit from two parents that both define a method `foo()` with different bodies, the compiler would not know which one the child should use. Languages that allow multiple class inheritance (like C++) need extra rules to resolve this. Java sidesteps it for classes entirely. ## How Java gives you 'multiple' behavior anyway A class can `implements` any number of **interfaces**. An interface is a contract of method signatures; since Java 8 it can also supply **default methods** (method bodies). So you get behavior from many sources via interfaces while keeping single *class* inheritance: ```java class Duck extends Bird implements Swimmer, Flyer { } ``` If two interfaces provide conflicting default methods, Java forces *you* to override and resolve it explicitly — so there is no silent ambiguity. ## Object: the root of everything If a class has no `extends` clause, the compiler implicitly inserts `extends Object`. Therefore **every** class is ultimately a descendant of `java.lang.Object`, and the whole set of classes forms one tree rooted at `Object`. That is why every object has methods like `toString()`, `equals()`, and `hashCode()`. ## Why it matters: polymorphism Because `Dog` is-a `Animal`, a variable typed `Animal` can refer to a `Dog`: `Animal a = new Dog();`. This **polymorphism** is the practical payoff of inheritance — you write code against the general type and it works for any subtype. ## Common boundaries - `final` classes cannot be extended (e.g. `String`). - A subclass cannot reduce the visibility of an overridden method. - Constructors are **not** inherited.

  • If Java forbids multiple class inheritance, how do you reuse code from several sources?
    Implement multiple interfaces (which can carry default method bodies) or use composition — hold instances of other classes as fields and delegate to them.
  • Can you extend a final class?
    No. A class marked final cannot be subclassed; that is why classes like String are final.

A family tree where every person has exactly one biological parent line you can name — you can't list two fathers — but you can join many clubs (interfaces) for extra skills.

saying these in an interview costs you the question

  • Saying Java supports multiple class inheritance — it does not (only multiple interfaces)
  • Claiming private members are inherited and usable by name in the subclass
  • Thinking constructors are inherited
  • Confusing extends (classes) with implements (interfaces)

context

open as a page

How do you call a parent class's overridden method from a subclass, and what does super refer to?

level: juniorimportance: must knowfreq 80%

basics

~10 s

Use super.methodName() to call the parent's version of a method that the subclass has overridden. super refers to the parent-class part of the current object.

open as a page

What does the `final` keyword do when applied to a class versus a method in Java?

level: juniorimportance: must knowfreq 70%

basics

~20 s

A final class can't be extended (no subclasses). A final method can't be overridden by a subclass, though the class itself can still be subclassed. Both lock down a piece of behavior so others can't change it.

open as a page

What conditions must a subclass method satisfy to override a method inherited from its superclass?

level: juniorimportance: must knowfreq 80%

basics

~20 s

The subclass method must have the same name and same parameter list as the superclass method, and the same (or a compatible) return type. If the name or parameters differ, it is not an override - it becomes a separate or overloaded method.

open as a page

How does super() work in constructors, and what are the rules for constructor chaining in an inheritance hierarchy?

level: middleimportance: must knowfreq 78%

basics

~10 s

super(...) calls a parent constructor and must be the first statement in a subclass constructor. If you don't write it, Java inserts a no-arg super() automatically so the parent is always initialized first.

open as a page

What is the difference between method overriding and method hiding in Java?

level: middleimportance: must knowfreq 72%

basics

~20 s

Overriding replaces an instance (non-static) method in a subclass; which version runs is decided at runtime by the object's actual type. Hiding happens with static methods (or fields): the subclass version masks the parent's, and which runs is decided at compile time by the declared type.

open as a page

How do overriding, overloading, and method hiding differ, and how does each get resolved?

level: middleimportance: must knowfreq 72%

basics

~20 s

Overriding replaces an inherited instance method with the same signature and is chosen at runtime by the object's real type. Overloading is several methods with the same name but different parameters, chosen at compile time. Hiding happens with static methods (or fields) and is resolved by the reference type, not the object.

open as a page

Why is java.lang.Object the universal superclass, and what does every class get from it?

level: middleimportance: should knowfreq 62%

basics

~10 s

Every Java class extends Object directly or indirectly, so all objects share a common type and inherit methods like toString(), equals(), and hashCode().

open as a page

When should you choose to make a class or method `final` as a design decision, and what are the trade-offs?

level: middleimportance: should knowfreq 50%

basics

~20 s

Make a class or method final when it isn't designed to be extended or changed — like value/immutable types or a security-critical method. The trade-off is lost flexibility: others can't subclass or override it, and some testing/mocking tools struggle with final.

open as a page

Why can't static methods be overridden in Java, and what happens if a subclass declares a static method with the same signature?

level: middleimportance: should knowfreq 55%

basics

~20 s

Static methods belong to the class, not to an object, so there's no object whose runtime type could pick a version — Java just uses the declared type at compile time. A same-signature static method in a subclass hides the parent's, it doesn't override it.

open as a page

What are covariant return types in method overriding, and why are they useful?

level: middleimportance: should knowfreq 55%

basics

~20 s

A covariant return type means an overriding method can return a more specific subtype than the method it overrides. For example, if the parent returns Animal, the child override may return Cat. It lets callers get the precise type without casting.

open as a page

When should you prefer inheritance (extends) versus composition, and what risks does deep inheritance introduce?

level: seniorimportance: should knowfreq 55%

basics

~20 s

Use extends only for a true is-a relationship where the subclass is a proper substitute for the parent. Otherwise prefer composition — hold an object as a field and delegate to it — to avoid tight coupling and fragile base classes.

open as a page

Why is the `final` keyword important for security and immutability, and why is `java.lang.String` final?

level: seniorimportance: should knowfreq 55%

basics

~20 s

Marking a class final stops anyone from subclassing it to inject malicious or behavior-changing code. String is final so an attacker can't subclass it to make a "string" whose value secretly changes after a security check, which keeps it safely immutable.

open as a page

If a subclass declares a field with the same name as its superclass, how is that field resolved when accessed through different reference types?

level: seniorimportance: should knowfreq 48%

basics

~20 s

Fields are never overridden, only hidden. Java picks the field based on the type of the reference you use, decided at compile time — not the actual object. So the same object can hold both the parent's and child's field, and a cast changes which one you read.

open as a page

Predict the output of a small hierarchy that mixes an overridden method with a hidden field, and explain each result.

level: seniorimportance: should knowfreq 40%

basics

~20 s

The overridden method runs the subclass version (chosen by the real object type). The hidden field is read from whichever reference type you use (chosen at compile time). So through a parent reference, you get the child's method but the parent's field value.

open as a page

What are the rules for declared exceptions when overriding a method, and why do they exist?

level: seniorimportance: should knowfreq 50%

basics

~20 s

An overriding method may throw the same checked exceptions, narrower (subtype) ones, or fewer - but it may not declare new or broader checked exceptions than the method it overrides. Unchecked (runtime) exceptions are unrestricted.

open as a page

Why is calling an overridable method from a constructor dangerous, and how does it relate to overriding rules?

level: principalimportance: should knowfreq 38%

basics

~20 s

If a superclass constructor calls a method that a subclass overrides, the subclass's version runs before the subclass's own fields are initialized. So the override can see uninitialized (null/zero) fields and behave wrongly. Avoid calling overridable methods from constructors.

open as a page

How does making a method `final` interact with the template-method pattern and JIT optimization, and what subtle pitfalls exist when finalizing methods in an inheritable class?

level: principalimportance: nice to knowfreq 28%

basics

~20 s

A final method is perfect for the fixed skeleton in the template-method pattern: the algorithm stays locked while subclasses fill in the open hook methods. Final methods also help the JIT inline calls since there's only one implementation. Pitfalls: a constructor calling an overridable method, and accidentally locking behavior subclasses legitimately need.

open as a page

Why is method/field hiding considered a code smell, and what design guidance follows from how Java resolves hidden members?

level: principalimportance: nice to knowfreq 26%

basics

~20 s

Hiding looks like overriding in the source but behaves oppositely — it's resolved by the declared type, not the object — so it surprises readers and causes subtle bugs. Guidance: don't redeclare static methods or shadow fields; keep fields private and expose behavior through overridable methods.

open as a page