this Keyword
this Keyword
this keyword in Java is a reserved word that refers to the current object in a method or constructor. It is used to clearly point to the current class variables when they have the same name as method or constructor parameters, helping to avoid confusion.
Accessing Class Attributes
Accessing class attributes means using or getting the values of variables (attributes) of a class through an object. These attributes store the data of a class and can be accessed to read or modify their values.
Sometimes, a constructor or method has a parameter with the same name as a class variable. In such cases, the parameter temporarily hides the class variable inside that method or constructor, which can create confusion while accessing the value.
Β
Example
public class Main {
Β // Class attributes (variables)
Β int x;
Β String name;
Β int age;
Β // Constructor with parameter (same name as class variable x)
Β public Main(int x, String name, int age) {
Β Β // "this.x" refers to class variable x
Β Β // x (right side) is parameter value
Β Β this.x = x;
Β Β // Assigning values to other class attributes
Β Β this.name = name;
Β Β this.age = age;
Β }
Β public static void main(String[] args) {
Β Β // Creating object and passing values to constructor
Β Β Main myObj = new Main(5, "Rahul", 20);
Β Β // Accessing class attributes using object
Β Β System.out.println("Value of x = " + myObj.x);
Β Β System.out.println("Name = " + myObj.name);
Β Β System.out.println("Age = " + myObj.age);
Β }
}