Non-class functions in Java

前端 未结 4 1433
广开言路
广开言路 2020-12-21 16:46

I\'m mostly a c/C++/objective-C programmer, presently working in Java on an android application. My question is simple: I want a utility function, preferably not associated

4条回答
  •  没有蜡笔的小新
    2020-12-21 17:26

    You can achieve the same "effect" by using a static import, by adding the following import in each file that you want to use it in:

    import static x.y.Class.someFunction;  // or x.y.Class.*;
    
    ...
    
    // some code somewhere in the same file
    someFunction();
    

    However, all methods in Java must be part of a class. Static imports just let you pretend (briefly) otherwise.

    P.S. This also works for static fields.

提交回复
热议问题