super Keyword in OOP (Java)
What is super?
The 'super' keyword in Java is a reference variable that is used to refer to the immediate parent class object.
It is commonly used in inheritance scenarios to access methods, variables, or constructors of the parent
class. The 'super' keyword helps in resolving ambiguities and in reusing code from the parent class.
Uses of super
1. To call the parent class constructor
2. To call the parent class method
3. To access the parent class variable
Calling Parent Constructor
Using 'super()' allows you to call the constructor of the parent class. This must be the first statement in the
child class constructor. Example:
class Parent {
Parent() { System.out.println("Parent constructor"); }
class Child extends Parent {
Child() {
super();
System.out.println("Child constructor");
Calling Parent Method
If a child class overrides a method of the parent class, you can use 'super.methodName()' to invoke the
original method of the parent class.
Example:
class Parent {
void show() { System.out.println("Parent show()"); }
}
super Keyword in OOP (Java)
class Child extends Parent {
void show() {
super.show();
System.out.println("Child show()");
Accessing Parent Variables
When a variable in a child class has the same name as in its parent class, 'super.variableName' is used to
access the parent class's variable.
Example:
class Parent {
int a = 10;
class Child extends Parent {
int a = 20;
void display() {
System.out.println("Child a: " + a);
System.out.println("Parent a: " + super.a);
Rules and Limitations
- 'super()' must be the first line in a constructor
- Cannot be used in a static context
- Cannot access private members of the parent class directly
When to Use super
- To resolve variable or method name conflicts
- To reuse parent class code
super Keyword in OOP (Java)
- To access parent class logic from overridden methods
Conclusion
The 'super' keyword is essential for managing inheritance in Java. It allows developers to write cleaner and
more maintainable code by reusing parent class functionality. Understanding when and how to use 'super' is
crucial for mastering OOP concepts in Java.