开发者

A static call problem in Java

I have a problem calling a static method from a class. Let me explain myself. I have an interface Foo and his implementation FooImpl which defines the method getFoo(); :

public interface Foo {
   ...
   public A getFoo();

   ....
}

public class FooImpl implements Foo { 

    public A getFoo(){
        ....
        return new A();
    } 
} 

This interface and his implementation is provided and I cannot modify them. In my program, I define a class called Bar in which the method getFoo is always called:

public class Bar {

   Foo foo

   public void fooBar(){
         ......
         foo.getFoo()
         ....
   }
} 

My problem is that I would to make a static call to the method fooBar of the class Bar but it is impossible since the method getFoo is not defined as static. For instance, I would like to do something lik开发者_如何学运维e this :

public class Bar2 {

  public void execute(){
     Bar.fooBar()
  }
}

How can I achieve that ?

Thanks for your advice

[EDIT] Sorry if I am not clear. The class Bar has a reference to Foo, so this is why it is possible to call getFoo in the class. And I can guarantee that Foo/FooImpl are properly initialized (not by me) and I just use the informations provided by this interface.


To call Bar.fooBar() in that way, it would have to be static, period.

You haven't shown how Bar gets an instance of Foo or FooImpl on which to call getFoo() - could there be a static Foo variable in Bar for example?

Basically there isn't enough information here, but sooner or later you'll have to have an instance of FooImpl at least, and quite possibly an instance of Bar, depending on its requirements.


It seems you want something like this in Bar:

public static void fooBar() {
  ...
  Foo foo = new FooImpl();
  ...
  foo.getFoo();
  ...
}


You cannot do that. The whole point of a non static method is that it requires an instance to be called against.

Typically, such a method will interact with the instance in some way like accessing its private data. It also means that calls to the method on different instances can return different results.


You can use new Bar().fooBar();


You have to make sure to create an instance of FooImpl inside static fooBar method like this:

public static void fooBar(){
         Foo fooImpl = new FooImpl(); // create an isntance
         fooImpl.getFoo(); // call it
         ....
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜