The this
and super
keywords provide a way to refer to the current class instance and the parent class respectively.
Understanding these keywords is essential to manage class inheritance and object references efficiently in Java.
The this
and super
keywords provide a way to refer to the current class instance and the parent class respectively.
Understanding these keywords is essential to manage class inheritance and object references efficiently in Java.
this
is a reference variable in Java that refers to the current object.
super
is a reference variable used to refer to the immediate parent class object.
this
keyword:
super
keyword:
Explains how the this
keyword works in Java.
this
Keyword
class Student {
int id;
String name;
Student(int id, String name) {
this.id = id; // 'this' distinguishes instance variable from parameter
this.name = name;
}
void display() {
System.out.println("ID: " + this.id + ", Name: " + this.name);
}
}
public class Main {
public static void main(String[] args) {
Student s = new Student(101, "John");
s.display();
}
}
super
Keyword
class Animal {
void sound() {
System.out.println("Animal makes a sound");
}
}
class Dog extends Animal {
void sound() {
System.out.println("Dog barks");
}
void parentSound() {
super.sound(); // calls Animal's sound method
}
}
public class Main {
public static void main(String[] args) {
Dog d = new Dog();
d.sound();
d.parentSound();
}
}
super
Constructor
class Person {
String name;
Person(String name) {
this.name = name;
}
}
class Employee extends Person {
int id;
Employee(String name, int id) {
super(name); // calls Person's constructor
this.id = id;
}
void display() {
System.out.println("Name: " + name + ", ID: " + id);
}
}
public class Main {
public static void main(String[] args) {
Employee e = new Employee("Alice", 1001);
e.display();
}
}
Using this
to avoid ambiguity during object creation in complex classes.
super
helps access overridden methods and parent constructors in subclass hierarchies.
Frameworks use this
and super
to manage code reuse and override behavior efficiently.
this
keyword in Java?The this
keyword refers to the current object instance and is commonly used to resolve naming conflicts between instance variables and parameters.
super
keyword used in Java?super
is used to access parent class members (variables, methods) and to call parent class constructors from a subclass.
this
?Yes, using this()
you can call another constructor of the same class to reuse initialization code (constructor chaining).