如何在不使用Java创建对象的情况下调用方法

如何在不使用Java创建对象的情况下调用方法

问题描述:

any1可以告诉我如何在不创建对象的情况下调用类的方法,但是通过引用

can any1 tell me how we can call the method of the class without creating object but the by reference

将这些方法设为静态. 参见
示例
make these methods static.
see
Example


并作为3.解决方案;

您可以在匿名类中对对象进行寻址:

and as a 3. solution;

you can address the object in a anonymous class:

public Foo(){

public void bar(){
  Object oObject = new Object();
  Object.addListener(new IListener{
      
       public void ObjectChanged(Event oEvent){
           Foo.this.funnyAction();
       }
    }
  }
}

}



它始终取决于调用对象的上下文.通常,对接您应该尽可能少地使用public static.



It always depends on the context of calling an Object. Butt in general you should use as less public static as possible.


如果您引用了该类的实例(其他人为您创建的实例),则只需调用该方法即可.另一方面,如果还没有,则必须使该方法静态(如果可能).
If you have a reference to an instance of the class (that someone else created for you) then just call the method. If, on the other hand, you haven''t it then you have to make the method static (if possible).