Java Essentials: this
and super
Keywords
In Java, this
and super
are two fundamental keywords that help you work with classes, objects, and inheritance. Let's dive into their uses and differences.
this
Keyword
The this
keyword refers to the current object of a class. It's used to:
- Refer to current class instance variables: To resolve ambiguity between instance variables and parameters with the same name.
- Improve code readability: By clearly indicating which variables belong to the current object.
Example:
public class Student {
String name;
public Student(String name) {
this.name = name; // 'this.name' refers to instance variable
}
}
super
Keyword
The super
keyword refers to the immediate parent class object. It's used to:
- Access parent class variables: When child and parent classes have fields with the same name.
- Call parent class methods: To invoke overridden methods from the parent class.
Example:
class Parent {
String color = "white";
void display() {
System.out.println("Parent method");
}
}
class Child extends Parent {
String color = "black";
void printColor() {
System.out.println(super.color); // prints "white" (parent)
System.out.println(color); // prints "black" (child)
}
void display() {
super.display(); // calls parent's display()
System.out.println("Child method");
}
}
Comparison of super
and this
super this
Reference Immediate parent class Current class instance
Constructor Calls parent constructor Calls current class constructor
Variables Accesses parent class variables Accesses current class variables
Methods Calls overridden parent methods Calls current class methods
By understanding this
and super
, you'll be used to write more efficient, readable, and maintainable Java code. These keywords are essential for working with classes, objects, and inheritance in Java.
Top comments (0)