this vs super Keyword in Java
When working with Java classes, two important keywords, this
and super
, help in handling instance variables and inheritance. In this blog, we will understand these keywords with explanations and examples.
What is this
Keyword?#
The this
keyword refers to the current instance of a class. It is mainly used to differentiate between instance variables and parameters with the same name, invoke constructors within the same class, and pass the current instance to a method.
Uses of this
Keyword#
- Referring to instance variables
- Calling another constructor in the same class
- Passing the current object as a parameter
- Returning the current instance from a method
Example: Using this
to refer to instance variables#
Output:#
Example: Using this
to call another constructor#
Output:#
What is super
Keyword?#
The super
keyword is used in inheritance to refer to the parent class. It is mainly used to access parent class members, invoke parent class methods, and call parent class constructors.
Uses of super
Keyword#
- Accessing parent class methods
- Calling the parent class constructor
- Accessing parent class variables
Example: Using super
to call parent class methods#
Output:#
Example: Using super
to call parent class constructor#
Output:#
Difference Between this
and super
#
Feature | this | super |
---|---|---|
Refers to | Current instance of the class | Parent class instance |
Used for | Accessing instance variables, methods, and constructors | Accessing parent class members and constructors |
Calls | Another constructor in the same class | Parent class constructor |
Can be used in static methods? | No | No |
Conclusion#
In this blog, we learned about the this
and super
keywords in Java. The this
keyword is used for referring to the current instance, differentiating instance variables, and calling constructors within the same class. The super
keyword is used to refer to the parent class, access its members, and call its constructor. Understanding these concepts is crucial for working with object-oriented programming and inheritance in Java.