class SomeClass {
public void someMethod(){}
public void otherMethod(){
//Calling someMethod()
}
}
当你调用一个实例方法时有什么不同:
--> someMethod(); OR this.someMethod();
vs
--> SomeClass.this.someMethod();
发布于 2018-07-25 01:53:51
与做以下事情没有区别:
//...
public void otherMethod(){
someMethod();
}
//...
去做
//...
public void otherMethod(){
this.someMethod(); // `this` in this case refers to the class instance
}
//...
现在如果你想
class SomeClass {
public static void someMethod(){}
public void otherMethod(){
//Calling someMethod()
}
}
你可以这样做:
//...
public void otherMethod(){
SomeClass.someMethod(); // as the method is static you don't need to call it from an instance using `this` or omitting the class
}
//...
最后,这种语法SomeClass.this.someMethod();
并不是在所有场景中都是正确的。下面是一个可以使用(正确)的示例:
class SomeClass {
public void someMethod(){}
public void otherMethod(){
//Calling someMethod()
}
class OtherClass {
public OtherClass() {
// OtherClass#someMethod hides SomeClass#someMethod so in order to call it it must be done like this
SomeClass.this.someMethod();
}
public void someMethod(){}
}
}
https://stackoverflow.com/questions/51504732
复制相似问题