Java实例方法的不同调用方式

时间:2018-07-24 17:46:11

标签: java instance

class SomeClass {
   public void someMethod(){}

   public void otherMethod(){
      //Calling someMethod()
   }
}

以如下方式调用实例方法有什么区别?

 --> someMethod(); OR this.someMethod();

vs

--> SomeClass.this.someMethod();

1 个答案:

答案 0 :(得分:3)

这样做没有什么区别:

//...
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(){}
    }
}