Skip to content
Tutorials Center
My learning

Topics

Lesson 55 of 201 ยท Object-Oriented Programming

Inheritance

Learn Java inheritance - extends and is-a, what subclasses inherit, constructor chaining, protected, single inheritance, final classes and Object as the root.

Inheritance lets you define a new class as a more specific version of an existing one. You write class EmailNotification extends Notification, and the new class automatically gets the fields and methods of Notification; you only add what's different. The existing class is the superclass (also parent or base class); the new one is the subclass (child or derived class).

The test for whether inheritance fits is the is-a relationship: an email notification is a notification, a savings account is an account. When that's true, inheritance removes duplicated code and lets one piece of code work with every kind of notification at once. When it isn't true, inheritance creates some of the most stubborn design problems in object-oriented code. This lesson covers the mechanics (extends, what's inherited, constructor chaining, protected, final, the Object root) and the judgment of when to use it.

extends: building on a class

Here a general Notification holds what every notification has. Two subclasses add their own fields and methods:

Java A superclass and two subclasses

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

Both subclasses can call send() and summary() without writing them, and subjectLine uses the inherited field text as if it were its own. Each subclass also has methods the other one lacks. A subclass is the parent plus extras; it can never be less than the parent.

What a subclass inherits

  • Inherited: all public and protected fields and methods, plus package-private ones when the subclass is in the same package.
  • Not accessible: private members. They still exist inside every subclass object (an EmailNotification has an attempts counter, and send() updates it), but subclass code can't name them. It works through inherited methods instead.
  • Not inherited at all: constructors. Each class declares its own, and a subclass constructor calls a superclass constructor with super(...).
  • Static members are reachable through the subclass (EmailNotification.someStaticMethod()), but they belong to the class that declared them.

A subclass can also override an inherited method, providing its own version with the same signature. That's the heart of Polymorphism, two lessons ahead; here's a taste:

Java
class SmsNotification extends Notification {
    @Override
    void send() {
        IO.println("[SMS gateway] " + text);
    }
}

Constructor chaining

Creating an EmailNotification builds one object, but that object has a Notification part and an EmailNotification part, and each class initializes its own part. So every constructor starts by calling a constructor of its superclass, all the way up the chain:

  • If you write super(...), that constructor runs.
  • If you don't, Java inserts super();, a call to the parent's no-argument constructor.

That second rule produces one of the most common compile errors with inheritance. If the parent has no no-arg constructor, a subclass that doesn't call super(...) explicitly can't compile. This example fails on purpose:

Java The parent has no no-argument constructor

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

The compiler reports constructor Employee in class Employee cannot be applied to given types; along with required: String and found: no arguments. Add super(name); as the first line of the Manager constructor and it prints creating a manager and then Ravi. The details (including what Java 25 allows before super(...)) and a step-by-step demo of the construction order are in The super Keyword.

protected and inheritance

Notification.text is protected, so subclasses can read it directly. attempts is private, so they can't. Which should you choose? Prefer private fields with protected or public methods: the superclass then keeps control of its own invariants, exactly as with any other caller (Encapsulation). A protected field is visible to every subclass anyone will ever write, and to the whole package (Access Modifiers), so it's hard to change later. A protected final field like text is a reasonable compromise because nobody can reassign it.

Object: the root of every class

A class that doesn't say extends extends java.lang.Object implicitly. So every class sits in one big tree with Object at the top, and every object inherits Object's methods: toString(), equals(), hashCode(), getClass() and a few more.

Java Walking up the inheritance chain

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

The loop prints Puppy, Dog, Animal and java.lang.Object. This is multilevel inheritance: Puppy inherits from Dog, which inherits from Animal. A Puppy is also a Dog, an Animal and an Object, which is why instanceof is true for all three and why you can store it in a variable of type Animal. That conversion, from a subclass to a superclass type, is called upcasting, and it happens automatically. Notice also that describe(), written in Animal, calls getClass(), which reports the actual class: Puppy.

The Object methods you'll override most are covered in The Object Class: equals, hashCode and toString.

Single inheritance

A Java class has exactly one direct superclass. class A extends B, C doesn't compile. Languages that allow multiple class inheritance must answer awkward questions, such as what happens when both parents define the same method or field (the "diamond problem"). Java avoids them for classes and gives you interfaces instead: a class can implement any number of interfaces, so it can be many types while inheriting state from only one class (Interfaces).

Hierarchies can still be wide (many subclasses of one parent, like EmailNotification and SmsNotification) and deep (Animal โ†’ Dog โ†’ Puppy). In practice, keep them shallow: two or three levels are usually plenty.

final classes and methods

Sometimes you want to forbid extension:

  • A final class can't be extended at all. String, Integer, LocalDate and every record and enum are final. That's how immutable classes stop subclasses from breaking their guarantees.
  • A final method can be inherited but not overridden. Use it for a method whose behavior other methods rely on.
Java
final class Token {
    // ...
}

class SpecialToken extends Token {}       // error: cannot inherit from final Token

class Account {
    final String id() { return "AC-1"; }
}

class Savings extends Account {
    @Override
    String id() { return "X"; }           // error: id() in Savings cannot override id() in Account
}                                          //        overridden method is final

Sealed classes offer a middle ground: extension is allowed, but only by subclasses you list.

Inherited code you didn't expect: the fragile base class

Inheritance couples a subclass tightly to the implementation of its parent, not just its public methods. Here a subclass of ArrayList tries to count every element ever added, overriding both add and addAll:

Java Overriding methods of a class you don't control

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

This version prints size: 4 and added: 4, and it's correct only because ArrayList.addAll happens not to call add internally. Other collections do: HashSet.addAll, for example, is inherited from AbstractCollection and calls add for each element, so the same subclass of HashSet would count every element twice. The subclass depends on a detail the parent never promised, and a future version could change. That's the fragile base class problem.

The usual cure is composition: instead of being a list, the class has a list in a private field and forwards calls to it. You'll compare the two approaches in Composition, Aggregation and Association.

When to use inheritance

Use inheritance when all of these hold:

  1. It's a real is-a relationship, everywhere and always. Every SavingsAccount is an Account.
  2. Subclass objects can stand in for parent objects without surprising anyone. This is the Liskov substitution principle (SOLID). The textbook counterexample: a Square extends Rectangle breaks code that sets a rectangle's width and height independently.
  3. The parent was designed for extension, ideally by you, with documented extension points, or it's abstract (Abstract Classes).

If you only want to reuse code, composition is usually better. If you want several unrelated classes to share a type, use an interface. Inheritance is the right tool for a family of closely related types that share both state and behavior.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Which members of a superclass can a subclass in the same package NOT use directly?

    Private members exist in the subclass object but are only accessible inside the class that declares them. The subclass reaches them through inherited methods.
  2. 2. class Base { Base(int x) {} } and class Sub extends Base { Sub() {} }. What happens?

    Without an explicit super(...) call, Java inserts super(). Base only has Base(int), so Sub must call super(someInt).
  3. 3. How many classes can a Java class directly extend?

    Java has single inheritance for classes. A class without extends implicitly extends Object. Multiple types come from implementing interfaces.
  4. 4. Given class Animal {}, class Cat extends Animal {} and Cat c = new Cat();, which is false?

    Cat's direct superclass is Animal, so getSuperclass() returns Animal. The other three statements are true because a Cat is an Animal and an Object.
  5. 5. Why is String declared final?

    Any String reference could otherwise point to a subclass object that behaves differently, breaking String's immutability and security guarantees.

Summary

  • class Sub extends Super makes Sub a more specific kind of Super; use it only for true is-a relationships.
  • Subclasses inherit public, protected (and same-package package-private) members; private members exist but aren't accessible; constructors aren't inherited.
  • Every constructor first calls a superclass constructor, explicitly with super(...) or implicitly with super(); a missing no-arg parent constructor is a compile error.
  • Every class ultimately extends Object; subclass objects can be upcast to any ancestor type.
  • Java has single inheritance for classes; interfaces provide multiple types.
  • final classes can't be extended and final methods can't be overridden.
  • Inheritance couples you to the parent's implementation (the fragile base class); prefer composition for plain code reuse.

Next: The super Keyword, where you'll call parent constructors and methods explicitly and watch the construction order unfold.