开发者

Why can't I call this function in Java?

开发者 https://www.devze.com 2022-12-20 01:50 出处:网络
import static com.example.hello.Tools.*; public class MAINCLASS{ public void run(){ runtools(); // this works
import static com.example.hello.Tools.*;
public class MAINCLASS{
   public void run(){
      runtools(); // this works
   }
   private class People{
      public void runpeople(){
          runtools(); // this does not work.
      }
   } 
}

Inside Tools...

Edit: When I roll over runtools() in People.runpeople()...I get this:

The method runtools() is undefined for the type MAINCLASS.People

publ开发者_运维知识库ic class Tools {
    public void runtools() {
     ....
    }
}

Does anyone know why?


You need to declare Tools#runtools() static to be able to import static it.

public class Tools {
    public static void runtools() {
        // ...
    }
}

Either that, or instantiate Tools and then call runtools() on it.

new Tools().runtools();


In reference to another question you asked recently related to this same class and it's issues: Why can't I put my functions in another class?

Does taking cletus' suggestion of removing the 'static' from the import call fix this issue as well? The 'static' bit is still there.


The call to runtools() should not work in either of those two cases, since runtools is not a static method - it needs an instance of the Tools object to be invoked on.


That code shouldn't work (at all) as you posted it because you only import static members of Tools, and runtools() is an instance method. If you were to make runtools() static, then both invocations of runtools() should work because it is in scope in both cases.


This does not compile. You cannot import a package, with the static keyword. The import needs to be a specific method.

So you need to write something like this to make it compile, and work:

import static com.example.hello.Tools.someMethod;

Also, the method you're importing needs to be static.

This makes you call a static method like it was declared in the scope of this class:

someMethod();
0

精彩评论

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

关注公众号