The super Keyword
Overview
If `this` refers to the current object, `super` refers to the Parent object.
When a child class inherits from a parent, sometimes it needs to talk to the parent directly. The most common scenario is during object creation: when you build a `Dog`, you must first build the `Animal` inside it. You use `super()` to call the parent's constructor.
1. Calling Parent Constructors
If the parent class requires data to be created (like an Animal needing an age), the child class MUST pass that data up using `super(age)`.
2. The Golden Rule of super()
When you use `super()` in a constructor, it MUST be the very first line of code. The parent foundation must be built before the child walls can go up.
Syntax
The Employee needs a salary. The Manager (which is an Employee) must pass the salary up to the parent using super.
class Employee {
double salary;
// Parent Constructor
public Employee(double salary) {
this.salary = salary;
}
}
class Manager extends Employee {
// Child Constructor
public Manager(double salary) {
// MUST be the first line! Calls Employee constructor.
super(salary);
}
}Common Pitfalls
- Forgetting to call `super()` when the parent class has a parameterized constructor. The compiler will stop you immediately.
Interview Tips
- Interviewers will show you a child class constructor with `super()` on the second line and ask what's wrong. You must confidently answer: 'It won't compile. super() must be line 1.'
Real-World Example
When making Android or iOS apps, you often extend the framework's Base classes and must call their setup methods using super.
public class LoginScreen extends BaseScreen {
@Override
public void start() {
super.start(); // Run the framework's critical setup first
System.out.println("Now running my custom login code...");
}
}