The <code>super</code> Keyword in Java
super refers to the immediate parent in the inheritance chain. You use it to (1) call a parent constructor, (2) call an overridden parent method, or (3) access a parent field that was shadowed.
Calling the parent constructor
public class Vehicle {
protected final String brand;
public Vehicle(String brand) { this.brand = brand; }
}
public class Car extends Vehicle {
private final int doors;
public Car(String brand, int doors) {
super(brand); // must be the first statement
this.doors = doors;
}
}
If you omit super(...), the compiler inserts super(). If the parent has no no-arg constructor, you must call super(...) explicitly.
Calling an overridden parent method
public class Animal {
public String speak() { return "generic sound"; }
}
public class Dog extends Animal {
@Override
public String speak() {
return super.speak() + " (actually a bark)";
}
}
Accessing a shadowed field
public class Parent { protected int x = 1; }
public class Child extends Parent {
protected int x = 2;
public void show() {
System.out.println(x); // 2 β child's field
System.out.println(super.x); // 1 β parent's
}
}
Shadowing fields is generally a bad idea β it creates confusion. Prefer different names.
super in interfaces (Java 8+)
public interface Greeter { default String hi() { return "hi"; } }
public interface LoudGreeter { default String hi() { return "HI!"; } }
public class Both implements Greeter, LoudGreeter {
@Override
public String hi() {
return Greeter.super.hi() + " / " + LoudGreeter.super.hi();
}
}
Common mistakes
- Using
super()withthis()β you can have at most one, and it must be first. - Skipping the parent constructor β if it has required parameters, the compiler won't let you.
- Shadowing fields by accident β a subclass field with the same name hides the parent's. Rename instead.
Related
Pillar: Java keywords. See also this, inheritance, constructors.