DEV Community

Ranjith Ranjith
Ranjith Ranjith

Posted on

this and super

this
this refers to a reference of the current class.
Java Object-Oriented Pr
this Keyword in Java
The this keyword in Java is a reference variable that refers to the current object.
It is used within an instance method to access members of the current object such as instance variables, methods, .

Usage
The this keyword is primarily used in the following scenarios:

 *To refer to the current class instance variable.
  *
    *To pass the current object as a parameter to a method.
Enter fullscreen mode Exit fullscreen mode

To return the current object from a method.
Ex
public class ThisExample {
int a;
int b;

ThisExample(int a, int b) {
    this.a = a;
    this.b = b;
}

void display() {
    System.out.println("a: " + this.a + ", b: " + this.b);
}

public static void main(String[] args) {
    ThisExample obj = new ThisExample(10, 20);
    obj.display();
}
Enter fullscreen mode Exit fullscreen mode

Super ::
super Keyword in Java
The super keyword in Java is used to refer to the immediate parent class object.
It is commonly used to access parent class methods and constructors, enabling a subclass to inherit and reuse the functionality of its superclass.

Usage
*To access a method from the superclass that has been overridden in the subclass

To be discus ::To invoke the current class method.

Reffer ::https://www.datacamp.com/doc/java/this

Top comments (0)