DEV Community

MANOJ K
MANOJ K

Posted on

This Keyword ::

This Keyword

  • this is a reference to the current object: this is used to refer to the current object of the class.

  • The this keyword refers to the current object in a method or constructor.

  • The this keyword is often used to avoid confusion when class attributes have the same name as method or constructor parameters.

  • this can be used to invoke constructors: this can be used to invoke one constructor from another constructor in the same class.

  • This is used to Differentiating instance variable and local variable /parameter with the same name.

class Human{
   String name;
   int age;
   int weight;
   int height;

Human (String name, int age, int weight, int height) {
     this.name = name;
     this.age = age;
     this.weight = weight;
     this.height = height;
     }



void displayDetails() {
     System.out.println("Name: " + name);
     System.out.println("Age: " + age);
     System.out.println("Weight: " + weight);
     System.out.println("Height: " + height);
    }

public static void main(String[] args) {
     Human M = new Human("Manoj", 21, 50, 168);
     M.displayDetails();


     Human M1 = new Human("Mani", 22, 72, 170);
     M1.displayDetails();

    }
}


OUTPUT:

Name: Manoj
Age: 21
Weight: 50kg
Height: 168cm

Name: Mani
Age: 22
Weight: 72kg
Height: 170cm


Enter fullscreen mode Exit fullscreen mode

Reference:

https://www.w3schools.com/java/ref_keyword_this.asp
https://www.w3schools.com/java/java_this.asp

Top comments (0)