Using this
with a class attribute (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 refers to the current object in a method or constructor.
The most common use of the this
keyword is to eliminate the confusion between class attributes and parameters with the same name (because a class attribute is shadowed by a method or constructor parameter). If you omit the keyword in the example above, the output would be "0" instead of "5".
this
can also be used to:
Read more about objects in our Java Classes/Objects Tutorial.
Read more about constructors in our Java Constructors Tutorial.
Read more about methods in our Java Methods Tutorial.
截取页面反馈部分,让我们更快修复内容!也可以直接跳过填写反馈内容!