Non-class functions in Java

前端 未结 4 1410
广开言路
广开言路 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.

    0 讨论(0)
  • 2020-12-21 17:40

    Also, following the programming best practices, You should define all such common, frequently used functionality in some utility class where you can define your functions or fields(probably constants- i.e. static and final attributes) that is going to be used/called at different places within the API.

    Although, you still need to import the Utility class. Else define such functionality in the top most parent class in your API hierarchy structure, that way you even don't have to import the class.

    Hope this helps. thanks....!!!

    0 讨论(0)
  • 2020-12-21 17:48

    Yeap import static..

    For instance:

    import static java.lang.Math.max; // Allowing to use max method anywhere in the source
    class SomeClass { 
        int m = max( 1, 2 );// m now is 2 due t Math.max( int, int ) 
    }
    
    0 讨论(0)
  • 2020-12-21 17:49

    You could use a static import:

    import static com.example.MyUtilityClass.*; // makes all class methods available
    // or
    import static com.example.MyUtilityClass.myMethod; // makes specified method available
    

    You don't see this used very often because, if overused, it causes harder-to-debug code (see the last paragraph at the link above).

    Here's a related question about when it's advisable to use this.

    0 讨论(0)
提交回复
热议问题