this and super in Java
In Java, this and super are special keywords used in inheritance and object-oriented programming.
thisrefers to the current object.superrefers to the immediate parent class object.
1. this Keyword
The this keyword refers to the current object of the class.
Uses of this
1. Distinguish Instance Variables from Parameters
class Student { String name; Student(String name) { this.name = name; } void display() { System.out.println(name); } }
Here, this.name refers to the instance variable, while name refers to the constructor parameter.
2. Call Current Class Method
class Student { void display() { System.out.println("Student"); } void show() { this.display(); } }
3. Call Current Class Constructor
this() can be used to call another constructor of the same class.
class Student { Student() { this("Anuradha"); } Student(String name) { System.out.println(name); } }
2. super Keyword
The super keyword refers to the immediate parent class.
Uses of super
1. Access Parent Class Variable
class Animal { String name = "Animal"; } class Dog extends Animal { String name = "Dog"; void display() { System.out.println(name); System.out.println(super.name); } }
Output
Dog Animal
Here, name refers to the child class variable, while super.name refers to the parent class variable.
2. Call Parent Class Method
class Animal { void sound() { System.out.println("Animal makes sound"); } } class Dog extends Animal { void sound() { System.out.println("Dog barks"); } void display() { super.sound(); sound(); } }
Output
Animal makes sound Dog barks
3. Call Parent Class Constructor
super() is used to call the constructor of the parent class.
class Animal { Animal() { System.out.println("Animal constructor"); } } class Dog extends Animal { Dog() { super(); System.out.println("Dog constructor"); } }
Output
Animal constructor Dog constructor
super() must be the first statement inside a constructor.
Difference Between this and super
this | super |
|---|---|
| Refers to the current class object. | Refers to the immediate parent class. |
| Accesses current class variables. | Accesses parent class variables. |
| Calls current class methods. | Calls parent class methods. |
this() calls another constructor of the same class. | super() calls the parent class constructor. |
| Used mainly within the current class. | Used mainly in inheritance. |
Important Points
thisrepresents the current object.superrepresents the parent class.this()calls another constructor in the same class.super()calls the parent class constructor.- Both
this()andsuper()must be the first statement in a constructor when used. - A constructor cannot use both
this()andsuper()as constructor calls at the same time.
Conclusion
The this keyword is used to work with the current class/object, while the super keyword is used to access members of the parent class. Both are important for handling constructors, variables, methods, and inheritance in Java.