我可以在方法中使用this
,还是错误的?
字段:
private int level;
private String name;
方法
public void check(String Name, int newlevel)
{
if (this.level < newlevel )
{
this.level = newslevel;
this.Name = Name;
System.out.println("." Name+" you are in the right level);
}
else
{
System.out.println("Sorry your are not on the right level" );
}
}
最佳答案
是的。你可以这样做。它经常用在 setter 中:
public void setX(int x) {
this.x = x;
}
在上面,如果您省略 this
,您只是将参数 x
设置为自身 - 这不是您想要的!因此,经常使用关键字final
:
public void setX(final int x) {
this.x = x;
}
在上面,如果您省略 this
,那么编译器会提示您将 x
设置为自身。
关于java - 在方法中使用 "this",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13169112/