Memra

extends, super() & constructor chaining

How a subclass inherits from a superclass — and the rules for calling super().

Extending a class

Inheritance lets one class reuse the fields and methods of another. The subclass is declared with extends:

public class Animal {
    String name;
    Animal(String name) { this.name = name; }
    void breathe() { System.out.println(name + " breathes"); }
}

public class Dog extends Animal {
    String breed;

    Dog(String name, String breed) {
        super(name);          // must be first statement
        this.breed = breed;
    }

    void fetch() { System.out.println(name + " fetches!"); }
}

super(...) calls the parent's constructor. Three hard rules:

  1. super(...) must be the first statement in the constructor body — placing any code before it is a compile error.
  2. If your constructor does not call super(...) explicitly, the compiler inserts an implicit super() (no-arg). If the parent has no no-arg constructor, this is a compile error.
  3. You cannot combine super(...) and this(...) as the first statement — pick one.

Chaining up the hierarchy: when you call new Dog("Rex", "Labrador"), the chain is Dog constructor → Animal constructor → Object constructor, in order. All three sets of fields are initialised before any constructor body completes.

NORMAL ~/memra/learn/java-from-zero/extends-and-super utf-8 LF