[ACCEPTED]-Non-class functions in Java-global

Accepted answer
Score: 17

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

import static x.y.Class.someFunction;  // or x.y.Class.*;


// some code somewhere in the same file

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

P.S. This 1 also works for static fields.

Score: 3

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 4 very often because, if overused, it causes 3 harder-to-debug code (see the last paragraph 2 at the link above).

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

Score: 1

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

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

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

Score: 0

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 ) 


More Related questions