Super Keyword in Java Explained
The super keyword in Java is a reference used inside a subclass to refer to its immediate parent (superclass). It is commonly used to access parent class constructors, methods, and variables that have been hidden or overridden.
Calling the Parent Class Constructor
When a subclass is created, super() can be used to explicitly call the parent class's constructor, which must be the first statement inside the subclass constructor.
class Animal {
Animal(String name) {
System.out.println("Animal: " + name);
}
}
class Dog extends Animal {
Dog(String name) {
super(name); // calls Animal's constructor
System.out.println("Dog created");
}
}
Accessing Parent Class Methods
If a subclass overrides a method from its parent, super.methodName() can be used inside the subclass to still call the parent's version of that method.
class Vehicle {
void start() { System.out.println("Vehicle starting"); }
}
class Car extends Vehicle {
void start() {
super.start(); // calls Vehicle's start()
System.out.println("Car starting");
}
}
Accessing Parent Class Variables
super can also be used to access a field from the parent class when the subclass has a field with the same name, avoiding ambiguity between the two.
super()— calls the parent class constructorsuper.method()— calls the parent class's version of a methodsuper.variable— accesses the parent class's field
super keyword is essential in inheritance hierarchies, since it lets a subclass build on top of parent behavior instead of completely replacing it.Master Java with Uncodemy
Hands-on training, live projects, and placement support in our Java Programming Course.