use*_*155 15 java methods this
用Java中的方法使用"this"怎么样?它是可选的还是有需要使用它的情况?
我遇到的唯一情况是在类中调用方法中的方法.但它是可选的.这是一个愚蠢的例子,只是为了表明我的意思:
public class Test {
String s;
private String hey() {
return s;
}
public String getS(){
String sm = this.hey();
// here I could just write hey(); without this
return sm;
}
}
Run Code Online (Sandbox Code Playgroud)
Jon*_*eet 36
您需要它的三个明显情况:
以下是这三个例子:
public class Test
{
int x;
public Test(int x)
{
this.x = x;
}
public Test()
{
this(10);
}
public void foo()
{
Helper.doSomethingWith(this);
}
public void setX(int x)
{
this.x = x;
}
}
Run Code Online (Sandbox Code Playgroud)
我相信也有一些奇怪的情况使用你需要的内部类,super.this.x但它们应该避免,因为非常模糊,IMO :)
编辑:我想不出任何为什么你想要它直接this.foo()方法调用的例子.
编辑:saua在晦涩的内部类例子上做出了贡献:
我认为晦涩的情况是:
OuterClass.this.foo()当foo()从具有foo()方法的Inner类中的代码访问外部类时.
| 归档时间: |
|
| 查看次数: |
18872 次 |
| 最近记录: |