Java super Keyword
In Java, the super keyword is used within a subclass to refer to its immediate parent class (superclass). It is primarily used when a subclass needs to access or reuse members from its parent class that are hidden, overridden, or shared.
The super keyword plays an important role in inheritance, helping maintain clear relationships between parent and child classes.
What Is the super Keyword in Java?
super provides a reference to the parent class and is commonly used in three ways:
- Access parent class methods
- Access parent class fields (attributes)
- Invoke the parent class constructor
1. Calling a Parent Class Method with super
When a subclass overrides a method, it can still call the original parent version using super.methodName().
Example: Calling overridden parent method
class Appliance {
public void powerOn() {
System.out.println("Appliance is powering on");
}
}
class WashingMachine extends Appliance {
@Override
public void powerOn() {
super.powerOn(); // call parent method
System.out.println("Washing machine is ready to use");
}
}
public class SuperMethodDemo {
public static void main(String[] args) {
WashingMachine wm = new WashingMachine();
wm.powerO
}
}
Output
Appliance is powering on
Washing machine is ready to use
When to use:
Use super when you want to extend — not completely replace — parent behavior.
2. Accessing Parent Class Fields with super
If a subclass defines a field with the same name as its parent, the parent field becomes hidden. Use super.fieldName to access it.
Example: Accessing hidden parent attribute
class Device {
String category = "Electronic Device";
}
class Laptop extends Device {
String category = "Portable Computer";
public void showCategories() {
System.out.println("Child: " + category);
System.out.println("Parent: " + super.category);
}
}
public class SuperFieldDemo {
public static void main(String[] args) {
Laptop laptop = new Laptop();
laptop.showCategories();
}
}
Output
Child: Portable Computer
Parent: Electronic Device
3. Calling the Parent Constructor with super()
Example: Constructor chaining with super
Output
Why Use the super Keyword?
Benefits
- Access overridden parent methods
- Resolve naming conflicts between parent and child members
- Reuse superclass constructors
- Extend behavior safely