可能重复:
我什么时候应该在课堂上使用"this"?
在引用实例的字段时,如何知道是否使用"this"?
例如:
return this.name
Run Code Online (Sandbox Code Playgroud)
我被教了一个有用的案例.即当输入参数与字段名称相同时:
public void setName(String name) {
this.name = name;
}
Run Code Online (Sandbox Code Playgroud)
除此之外,"这个"似乎不需要..还有什么其他案例?
如果有一个类的构造函数太多,可以使用它来调用其他构造函数.示例:
public class TeleScopePattern {
private final int servingSize;
private final int servings;
private final int calories;
private final int fat;
public TeleScopePattern(int servingSize, int servings) {
this(servingSize, servings, 0);
}
public TeleScopePattern(int servingSize, int servings, int calories) {
this(servingSize, servings, calories, 0);
}
public TeleScopePattern(int servingSize, int servings, int calories, int fat) {
this.servingSize = servingSize;
this.servings = servings;
this.calories = calories;
this.fat = fat;
}
}
Run Code Online (Sandbox Code Playgroud)
在少数情况下你必须使用它:
如果您具有相同的字段名称和方法参数/局部变量,并且您想要读/写该字段
当您想要从内部类访问外部类的字段时:
class Outer {
private String foo;
class Inner {
public void bar() {
System.out.println(Outer.this.foo);
}
}
}
Run Code Online (Sandbox Code Playgroud)this(arg1, arg2); 所有其他用法只是一种风格问题.
| 归档时间: |
|
| 查看次数: |
473 次 |
| 最近记录: |