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:
super(...)must be the first statement in the constructor body — placing any code before it is a compile error.- If your constructor does not call
super(...)explicitly, the compiler inserts an implicitsuper()(no-arg). If the parent has no no-arg constructor, this is a compile error. - You cannot combine
super(...)andthis(...)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.