Java Inheritance and the super Keyword

Java inheritance lets a subclass reuse and specialize an accessible superclass contract.

Lesson 56 of 127Intermediate14 min read

Java inheritance lets a subclass reuse and specialize an accessible superclass contract. extends creates that relationship, while super reaches superclass behavior or constructors. The examples distinguish inherited methods, overridden methods and construction order so you can use inheritance without confusing it with copying an object.

Review the related foundation lesson when you need a prerequisite. The complete programs below use Java 17-compatible syntax.

Subclass relationships

extends creates a subclass of one superclass. Java supports one direct class superclass, while a class can implement several interfaces.

A subclass object includes the instance state required by its superclass and its own declared fields. Inherited accessible methods can operate on that state. Private superclass members are not directly accessible from the subclass, although superclass methods can still use them. Prefer calling appropriate superclass operations instead of weakening field visibility merely to allow every subclass to manipulate internal details.

Inherited members and constructor requirements

A subclass inherits eligible members but cannot directly access private superclass fields. Superclass methods can provide controlled access to their behavior.

The super(...) constructor invocation initializes the superclass portion before the Java 17 subclass constructor body runs. If you omit it, Java inserts super() unless the constructor delegates with this(...). That implicit call requires an accessible no-argument superclass constructor. Constructors are not inherited: adding an overload in the superclass does not automatically create the corresponding subclass overload.

Superclass construction and calls

super(...) invokes a superclass constructor; super.method() invokes a superclass implementation rather than an overriding version on the current object.

super.method() deliberately selects an accessible superclass implementation. An ordinary overridden call through a superclass reference instead dispatches to the runtime object's implementation. A subclass can call super to extend behavior, such as adding a prefix to an existing description. It should not call the superclass method merely because the syntax is available; the combined behavior should still satisfy the superclass contract.

Inheritance versus composition

Inheritance should represent a substitutable relationship. Composition is often clearer when one object merely uses another rather than being a specialized version of it.

A class can extend one direct superclass, while implementing multiple interfaces. Use inheritance for a meaningful substitutable relationship: a SavingsAccount is an Account if callers can use it according to the Account contract. Use composition for has-a relationships such as a Report that uses a Printer. Deep hierarchies can scatter behavior across many files and make initialization harder to follow.

Running the examples

Save name.java, compile it with javac --release 17 name.java, and run java name. Use each program's own public class name and filename.

How BookVanInheritance produces its output

The subclass constructor passes the shared name to its superclass. That superclass stores the name before the subclass adds its own detail. When the example asks the child for a description, the override can reuse the parent description through super and add the specialized part. This combines behavior without creating a separate parent object.

How ConstructionOrder produces its output

Child has no explicit super call, so Java 17 inserts super() at the beginning of its constructor. Parent's constructor prints first, then Child's constructor body prints. The output represents two constructor bodies initializing one Child object. It does not mean that main constructed a separate Parent and a separate Child.

How InheritedDescription produces its output

The variable has the declared type Label, but its object is a FragileLabel. The ordinary text call dispatches to FragileLabel.text. Inside that override, super.text explicitly calls Label's implementation and obtains Parcel. Appending the specialized suffix produces the printed text. The superclass reference type does not disable overriding.

Inherited members do not duplicate a separate parent

A BookVan is one object that includes the route field required by Vehicle and the crates field declared by BookVan. Calling super(route) initializes the Vehicle portion of that object; it does not assign a separate Vehicle object to a hidden variable. Later, super.description reads the route already stored there. For practice, add another subclass with a different description but keep the same route constructor contract. Store both objects in Vehicle variables and call description. Then remove the explicit super call from a subclass constructor and observe why compilation fails when Vehicle has no accessible no-argument constructor.

Inheritance and independent collaborators

Inheritance does not prevent a subclass from also using composition. A BookVan can extend Vehicle for its route contract while holding a separate Inventory object that manages crates. The inventory is a collaborator rather than a superclass. This separation is helpful when inventory behavior must be reused by unrelated object types. Before adding an override, identify the parent method's promised result and accepted inputs. If a parent description promises non-null text, a subclass should preserve that promise. Java checks signatures and visibility, but it cannot prove every business expectation. Tests that exercise subclasses through parent references help expose violations that a direct subclass-only test can miss.

Java Summary

  • extends creates a subclass of one superclass. Java supports one direct class superclass, while a class can implement several interfaces.
  • A subclass inherits eligible members but cannot directly access private superclass fields. Superclass methods can provide controlled access to their behavior.
  • super(...) invokes a superclass constructor; super.method() invokes a superclass implementation rather than an overriding version on the current object.
  • Inheritance should represent a substitutable relationship. Composition is often clearer when one object merely uses another rather than being a specialized version of it.
  • Continue with Java exercises, Java quizzes and the Java study roadmap.

Java Examples

Each example shows the code, the output it produces and what each part does.

Example 1

Java Inheritance and the super Keyword in a complete program

Java
public class BookVanInheritance  {
    static class Vehicle  {
        final String route;
        Vehicle(String route) {
            this.route=route;
        }
        String description() {
            return route;
        }
    }
    static class BookVan extends Vehicle  {
        final int crates;
        BookVan(String route,int crates) {
            super(route);
            this.crates=crates;
        }
        @Override String description() {
            return super.description()+" carries "+crates+" crates";
        }
    }
    public static void main(String[] args)  {
        BookVan van = new BookVan("Harbor", 18);
        System.out.println(van.description());
    }
}
Output
Harbor carries 18 crates
Line-by-line explanation
  1. Line 23Evaluates van.description() and prints Harbor carries 18 crates.
Example 2

Superclass initialization comes first

Java
public class ConstructionOrder  {
    static class Parent  {
        Parent()  {
            System.out.println("parent");
        }
    }
    static class Child extends Parent  {
        Child()  {
            System.out.println("child");
        }
    }
    public static void main(String[] args)  {
        new Child();
    }
}
Output
parent
child
Line-by-line explanation
  1. Line 4Evaluates "parent" and prints parent.
  2. Line 9Evaluates "child" and prints child.
Example 3

Extending a superclass method

Java
public class InheritedDescription  {
    static class Label  {
        String text()  {
            return "Parcel";
        }
    }
    static class FragileLabel extends Label  {
        @Override String text()  {
            return super.text() + " fragile";
        }
    }
    public static void main(String[] args)  {
        Label label = new FragileLabel();
        System.out.println(label.text());
    }
}
Output
Parcel fragile
Line-by-line explanation
  1. Line 14Evaluates label.text() and prints Parcel fragile.

Java FAQ

Are constructors inherited?

No. A subclass declares its own constructors. Each must initialize the superclass through an accessible constructor, directly or through another constructor in its class. Inherited methods and constructor availability are separate language rules.

Can a subclass access every protected member on any parent object?

Not across packages. Protected instance access from a subclass in another package has receiver restrictions. Inside the same package, protected also grants package access. Treat protected as a carefully bounded extension hook rather than as public access.

In what order are constructors run with inheritance?

From the top of the hierarchy down. Creating a BookVan first runs Object's constructor, then Vehicle's, then BookVan's own body. Each class's field initialisers run just before its constructor body, which is why a superclass constructor can't yet see subclass field values.

Can I call a grandparent's method with super.super?

No. super.super.method() isn't valid Java. A subclass can only reach its direct superclass's version with super.method(). If the grandparent's behaviour is needed, the parent class must expose it, for example by not overriding the method or by providing a separate method.

Can super be used in a static method?

No. super, like this, refers to the current object, and a static method has no current object. Static methods are called through a class name, such as Vehicle.describeAll().

Java Exercises

Answer each one and check it instantly. If you get stuck, open the hint before the answer.

Multiple choiceeasy

What does super(...) invoke?

Multiple choicemedium

A Label reference holds a FragileLabel. Which text override runs?

Java Quiz

2 questions to check what you learned.

  1. Which relationship usually suggests composition?

    • A report uses a printer
    • A savings account satisfies an account contract
    • A specialized label satisfies a label contract
  2. How many direct superclasses can a Java class extend?

    • One
    • Any number
    • One per constructor