The super keyword is used to access members of an immediate parent class, such as its variables, methods, or constructors. Since every Java class implicitly extends Object if no other superclass is specified, a class technically always has a superclass. However, using super to access members that do not exist in the parent class will result in a compilation error.
Key Points: • super refers to the immediate parent class of the current class. • Every Java class indirectly inherits from the Object class. • super can be used only when there is an accessible member or constructor in the parent class. • Attempting to access a non-existent parent member using super causes a compilation error. • super is commonly used to call parent constructors, methods, and variables hidden by subclass members.
Example: If a parent class contains a method, the child class can access it using super.
Code Example:
class Parent {
void display() {
System.out.println("Parent Method");
}
}
class Child extends Parent {
void show() {
super.display();
}
}
public class Demo {
public static void main(String[] args) {
Child child = new Child();
child.show();
}
}Output:
Parent Method
Invalid Usage:
class Employee {
void display() {super.display(); // Compilation Error
}
}Compilation Error:
cannot find symbol
In this case, Employee directly extends Object, and Object does not contain a display() method. Therefore, the compiler cannot resolve the call.
Important Note:
Even when a class does not explicitly extend another class:
class Employee {
}Java automatically treats it as:
class Employee extends Object {
}Therefore, a class always has Object as its ultimate superclass.
Common Uses of super:
• Access parent class variables
super.name;
• Invoke parent class methods
super.display();
• Call parent class constructors
super();
Interview Tip: A concise interview answer is:
"The super keyword is used to access members of the immediate parent class. Since every Java class implicitly extends Object, a class always has a superclass. However, using super to access a parent member that does not exist results in a compilation error."