The super Keyword
Overview
The super keyword is the direct counterpart to this. While this refers to the current object, super acts as a direct hotline to the Parent (Superclass) of the current object.
It is primarily used in two scenarios:
1. Calling the Parent's Constructor: When a child object is instantiated, its parent MUST be instantiated first. super() is used inside the child's constructor to pass required data up to the parent's constructor.
2. Accessing Overridden Methods: If a child class creates a method with the exact same name as the parent (Overriding), the child's method hides the parent's method. You can use super.methodName() to forcefully execute the parent's original version of the code.
Syntax
class Employee {
String company;
// Parameterized Parent Constructor
public Employee(String company) {
this.company = company;
}
public void work() {
System.out.println("Doing generic work.");
}
}
class Developer extends Employee {
String language;
public Developer(String company, String language) {
// 1. MUST call parent constructor FIRST!
super(company);
this.language = language;
}
@Override
public void work() {
// 2. Calling the parent's overridden method
super.work();
System.out.println("Also writing " + language + " code.");
}
}Common Pitfalls
- Placing
super()on the second line of a constructor. A call to the parent's constructorsuper(...)MUST be the absolute first line of the child's constructor. The JVM strictly enforces that the parent is fully constructed before the child is allowed to do anything. - Missing default constructor errors. If a Parent class only has a parameterized constructor (e.g.,
Parent(int x)), the Child class will fail to compile unless you explicitly write a constructor in the Child that callssuper(x). The compiler's invisiblesuper()call only looks for an empty constructor!
Interview Questions
this() and super() in the exact same constructor?No. Both this() (calling another constructor in the same class) and super() (calling the parent's constructor) demand to be the absolute very first statement in a constructor block. Therefore, they are mutually exclusive.
super() in a child class constructor?The Java compiler automatically injects an invisible super(); (a call to the parent's no-argument constructor) on the first line. If the parent doesn't have a no-argument constructor, compilation fails.
Real-World Example
When creating custom UI components (like a Custom Button that plays a sound), developers override the parent onClick method. They use super.onClick() to ensure all the standard UI visual animations still trigger, before adding their custom sound logic.
public class AudioButton extends StandardButton {
@Override
public void onClick() {
// Execute the parent's complex visual animation logic
super.onClick();
// Execute my custom logic
speaker.playSound("click.mp3");
}
}Check Your Knowledge
Test your understanding of The super Keyword with these quick questions.