Understanding this and super keyword in Java
Shivam Verma
4? @Codechef | Specialist @Codeforces | Knight @LeetCode | Software Developer | Problem Solver | Java | Python | MySQL | Immediate Joiner
In Java, this and super are special keywords that help you work with objects and inheritance. Here’s a quick look at what they do:
The this Keyword
this refers to the current object in a class. It’s useful for:
Distinguishing Variables: When a method parameter has the same name as an instance variable, use this to refer to the instance variable.
public Person(String name) {
this.name = name; // Refers to the instance variable
}
Calling Other Methods: You can use this to call other methods in the same class.
this.display(); // Calls the display method
Passing the Current Object: You can pass the current object to another method.
driver.drive(this); // Passes the current instance
The super Keyword
super is used to access members (like methods and variables) of the parent class. Here’s how it works:
Calling Parent Constructors: Use super() to call the parent class's constructor.
super(); // Calls the parent class constructor
Accessing Overridden Methods: If a method is overridden in the child class, use super to call the parent class method.
super.sound(); // Calls the sound method from the parent class
Accessing Parent Fields: If a field is shadowed by a child class field, use super to refer to the parent class's field.
System.out.println(super.name); // Refers to the parent's name
Conclusion
Using this and super helps you write clearer and more organized Java code. They allow you to easily reference the current object and access members of the parent class, making your programming more effective.