Utilizing “this” with a class attribute named “x”:
public class Main { int x;
// Constructor with a parameter public Main(int x) { this.x = x; }
// Call the constructor public static void main(String[] args) { Main myObj = new Main(5); System.out.println(“Value of x = “ + myObj.x); } } |
The this keyword denotes the current object within a method or constructor.
The this keyword is frequently employed to disambiguate between class attributes and parameters sharing the same name, especially when a class attribute is overshadowed by a method or constructor parameter. In the provided example, excluding the keyword would yield an output of “0” instead of “5”.
Additionally, “this” can be employed to: