super Keyword
In short: A reference to the superclass within a subclass — enables access to overridden methods or fields of the superclass, even if the subclass has defined its own versions with the same name.
In more detail: Often used in constructors of subclasses, to first call the superclass’s constructor and take over its initialization, before the subclass sets its own additional fields. Without super in an overridden method, the superclass’s original implementation would no longer be reachable from within the subclass.
In Depth
class Animal {
String name;
Animal(String name) {
this.name = name;
}
void describe() {
System.out.println("My name is " + name);
}
}
class Dog extends Animal {
String breed;
Dog(String name, String breed) {
super(name); // calls Animal's constructor
this.breed = breed;
}
void describe() {
super.describe(); // calls the ORIGINAL method from Animal
System.out.println("I am a " + breed);
}
}Two main uses of super:
super(...)as a constructor call: if used, has to be the very first statement in the subclass’s constructor — the superclass has to be fully initialized before the subclass begins its own initialization. Ifsuper(...)isn’t called explicitly, many languages automatically insert an implicit call to the superclass’s parameterless constructor — if that doesn’t exist (e.g. because the superclass only offers a constructor WITH parameters), an explicitsuper(...)call is mandatory.super.method()as a method call: specifically calls the superclass’s version, even if the subclass has overridden the same method — useful for EXTENDING the original behaviour instead of completely replacing it (as in the example above: Dog adds its own output to the inherited base description instead of replacing it).
Without super.method() in an overridden method, the superclass’s original implementation would effectively be lost from within the subclass — its entire code would have to be duplicated instead of reused, which would contradict the basic idea of inheritance.
See also: Inheritance, Constructors, this Keyword