The super Keyword: Connecting to the Parent
In Java, the super keyword is a reference variable used to refer to the immediate parent class object. Think of it as a direct hotline to the "Superclass." It is the bridge that allows a child class to reach back and use logic or data from its parent.
There are three main ways to use super.
1. Using super() to Call Parent Constructors
This is the most common use. When you create a child object, it must initialize its parent parts first. Java calls the parent’s no-arg constructor automatically, but if the parent has a parameterized constructor, you must call it manually using super().
Rule:
super()must be the very first statement in the child constructor.
class Device {
String brand;
Device(String brand) {
this.brand = brand;
}
}
class Smartphone extends Device {
int ram;
Smartphone(String brand, int ram) {
super(brand); // Sends "brand" up to the Device constructor
this.ram = ram;
}
}
2. Using super to Access Parent Methods
Sometimes a child overrides a method but still wants to run the parent’s version of that method as part of its own logic.
class Hero {
void attack() {
System.out.println("The hero attacks!");
}
}
class Archer extends Hero {
@Override
void attack() {
super.attack(); // Runs the original "The hero attacks!"
System.out.println("Archer fires an arrow!");
}
}
3. Using super to Access Parent Fields
If a child class has a variable with the same name as a parent class variable (Shadowing), super is used to tell Java you want the one from the parent.
class Parent {
String name = "Parent Name";
}
class Child extends Parent {
String name = "Child Name";
void display() {
System.out.println(name); // Prints "Child Name"
System.out.println(super.name); // Prints "Parent Name"
}
}
💻 Full Practical Example: The Bank System
Copy this code to see how super ensures the parent logic is preserved while the child adds its own features:
class Person {
String name;
Person(String name) {
this.name = name;
}
void deposit(double amount) {
System.out.println(name + " deposited: $" + amount);
}
}
class Student extends Person {
double scholarship;
Student(String name, double scholarship) {
super(name);
this.scholarship = scholarship;
}
@Override
void deposit(double amount) {
// Call parent method
super.deposit(amount);
// Extra behavior for Student
System.out.println(name + " received scholarship bonus processing!");
}
}
public class Main {
public static void main(String[] args) {
Student s1 = new Student("Ahmed", 500);
s1.deposit(200);
}
}
💡 Challenge: The Super Vehicle
- Create a class
Vehiclewith a constructor that takesmaxSpeed. - Create a subclass
Truckthat has an extra fieldpayloadCapacity. - Use
super()in theTruckconstructor to set themaxSpeed. - Create a method in
Truckthat prints both the speed (from the parent) and the capacity.