Skip to content
Tutorials Center
My learning

Topics

Lesson 56 of 201 ยท Object-Oriented Programming

The super Keyword

Learn Java's super keyword - calling parent constructors, extending overridden methods, reaching hidden fields, constructor order and the Java 25 prologue.

When a class extends another, it sometimes needs to talk to its parent explicitly. It must run the parent's constructor before its own. It might override a method but still want the parent's version to do part of the work. The keyword for all of this is super. Where this means "the current object, seen as its own class", super means "the current object, seen as its parent class".

super comes in three forms: super(...) calls a parent constructor, super.method() calls the parent's version of a method, and super.field reaches a parent field hidden by a subclass field. This lesson covers each, then traces the exact order in which a three-level object is built, and finishes with the classic trap of calling an overridable method from a constructor. You should know Inheritance and The this Keyword first.

super(...): calling the parent constructor

Every constructor begins by running a constructor of its superclass, so the parent part of the object is ready before the child part is set up. You choose which one with super(...):

Java
class Vehicle {
    private final String plate;

    Vehicle(String plate) {
        this.plate = plate;
    }
}

class Truck extends Vehicle {
    private final int maxLoadKg;

    Truck(String plate, int maxLoadKg) {
        super(plate);                 // Vehicle sets up its own field
        this.maxLoadKg = maxLoadKg;   // then Truck sets up its own
    }
}

The rules:

  • If a constructor doesn't call super(...) or this(...), Java inserts super();, so the parent needs a no-argument constructor in that case (Inheritance shows the compile error).
  • A constructor calls either super(...) or this(...), at most once, never both. With this(...), the other constructor of the same class is responsible for calling super(...). One way or another, exactly one super(...) call runs per class level.
  • super(...) can only appear in constructors.

Code before super(...) in Java 25

Until Java 25, super(...) had to be the very first statement. That made a common task awkward: validating or preparing arguments before passing them up. Java 25's flexible constructor bodies allow statements before super(...), a part called the prologue, as long as they don't use the object being built: no reading or calling its instance members and no passing this anywhere. (Assigning the subclass's own fields there is also allowed.)

Java Validating arguments before super(...)

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 invalid truck is rejected before Vehicle's constructor ever runs: there's no Vehicle constructor runs line before Refused. On Java 24 and earlier you'd write the same check inside a static helper method called as super(check(plate)); you'll still see that style in older code.

The construction order, step by step

With several levels of inheritance, each level initializes its own part, starting from the top. For new Puppy() where Puppy extends Dog extends Animal:

  1. Static initialization happens first, once per class, parent before child (if the classes haven't been used yet).
  2. The Puppy constructor is called. Its first action is the super(...) call (after any prologue), which calls Dog's constructor, which calls Animal's, which calls Object's.
  3. Object's constructor returns. Then Animal's instance field initializers and instance blocks run, then the rest of Animal's constructor body.
  4. The same happens for Dog, then for Puppy.

So constructors are entered bottom-up but their bodies finish top-down. Seeing it is easier than reading it:

Java Watching a three-level object being built

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 static blocks appear only for the first puppy, parent first. For each object, the Puppy prologue runs first (it's before super()), then everything else flows from Animal down to Puppy, with each class's field initializers running just before its own constructor body.

super.method(): extending inherited behavior

When a subclass overrides a method, the parent's version is still there. super.method() calls it, so the override can add to the parent's behavior instead of replacing it:

Java Overrides that build on the parent's version

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.

Three things to notice:

  • DiscountedProduct.toString calls super.toString(), and inside that parent method, finalPrice() still runs the subclass's override. super. only affects the one call it's written on; method calls inside the parent's code are dispatched to the real object as usual. That's why the book prints 15.0, not 20.0.
  • super.labels() gives the parent's list, and the override adds to it. This "call super, then extend" pattern is the main reason super.method() exists.
  • Without super., calling finalPrice() inside the override would call itself and recurse until a StackOverflowError.

No super.super

super only reaches one level up. super.super.toString() doesn't compile. If Puppy needs Animal's behavior that Dog overrode, that's a sign the design should change, perhaps by giving Animal a separate, non-overridden method both can call. The parent decides what its subclasses see, and skipping a level would break that.

super.field: reaching hidden fields

A subclass can declare a field with the same name as a parent field. It doesn't override it (fields are never polymorphic); it hides it, and the object then contains two separate fields. super.name reaches the parent's one:

Java Two fields with the same name

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.

Notice the last two lines: which field you get depends on the declared type of the variable, not the actual object. That's the opposite of how methods behave, and it confuses everyone who meets it. The practical advice is simple: don't hide fields. Keep fields private and give subclass fields their own names; then super.field is never needed.

super with interface default methods

Interfaces can have default methods with a body (Interfaces). If a class implements two interfaces with the same default method, it must override it, and it can call a specific interface's version with InterfaceName.super.method():

Java Choosing between two default methods

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.

Without the override, the compiler reports that SmartWatch inherits unrelated defaults for status() from both types. Phone.super.status() works only for interfaces the class implements directly.

The trap: overridable methods in constructors

Because the parent's constructor runs before the subclass's fields are initialized, calling an overridable method from a parent constructor can run subclass code on a half-built object. This example doesn't crash, but it prints wrong values:

Java A parent constructor calling an overridden method

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 first line printed is render: null, volume 0. During super(label), Button's constructor calls render(), which dispatches to LoudButton.render (methods always go to the real object). But LoudButton's part of the object hasn't been initialized yet: its field initializers run only after super(...) returns, so style is still null and volume is still 0. The later render() call, made after construction, prints the right values.

Bugs like this are hard to spot because nothing fails at the moment it happens; a null just turns up somewhere later. The rule: a constructor should only call methods that are private, static or final, which subclasses can't override. If a class really needs a setup hook, document it loudly, or call the hook after construction from a factory method.

Java 25's prologue gives subclasses a defense of their own: a field without an initializer may be assigned before super(...), so it's already set when the parent calls back:

Java
LoudButton(String label) {
    this.volume = 11;      // allowed in the prologue (Java 25): volume has no initializer
    super(label);          // Button's call to render() now sees volume 11
}

Where super can't be used

  • In static methods. Like this, super refers to the current object, and static code has none.
  • To reach private members. super.attempts fails if attempts is private in the parent. super changes which class's version you get, not the access rules.
  • Across more than one level. There's no super.super.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. class A { A() { IO.print("A"); } }, class B extends A { B() { IO.print("B"); } }, class C extends B { C() { IO.print("C"); } }. What does new C() print?

    Each constructor implicitly calls super() first, so C's constructor calls B's, which calls A's. The bodies then finish top-down - A, B, C.
  2. 2. In an override of toString(), what does super.toString() do?

    super.method() runs the immediate parent's implementation on the current object. It's the standard way to extend inherited behavior.
  3. 3. A parent constructor calls an overridable method that the subclass overrides to print a subclass int field initialized to 5. What does that first call print?

    The parent constructor runs before the subclass's field initializers, so the override sees the field's default value, 0.
  4. 4. Which of these is allowed in a Java 25 constructor before super(...)?

    The prologue may use parameters, local variables and static members, and may assign the class's own uninitialized fields, but it must not use the object under construction in any other way.
  5. 5. Parent has a field String name = "P" and Child extends Parent declares its own String name = "C". What does Parent p = new Child(); IO.println(p.name); print?

    Fields aren't overridden, they're hidden, and field access is chosen by the variable's declared type. p is declared as Parent, so it reads Parent's field.

Summary

  • super(...) calls a parent constructor; without it Java inserts super(). A constructor calls super(...) or this(...), not both.
  • Since Java 25, statements that don't use the new object (validation, preparing arguments, assigning the class's own uninitialized fields) may come before super(...).
  • Objects are built top-down: static setup parent-first, then for each level its field initializers and constructor body, from Object down to the actual class.
  • super.method() runs the parent's version on the current object; calls inside that method still dispatch to overrides.
  • super.field reaches a hidden parent field; better not to hide fields at all. There's no super.super.
  • Interface.super.method() picks one of several conflicting default methods.
  • Don't call overridable methods from constructors: the subclass's fields aren't initialized yet.

Next: Polymorphism and Method Overriding, where one variable can hold many kinds of objects and each one behaves in its own way.