Search code examples
javaclassstaticglobal

Java - Declare Class Once Use Anywhere


Very simple problem but I'm not understanding static correctly.

I have java file which holds my main and its call testMain.

With my testMain it makes many classes with use other classes.

E.g. testMain>>GUI and testMain>>model and testMain>>controller

Now I have a class called generatorTester which I would like to declare once like:

public static utils.generatorTester randomGen = new utils.generatorTester ();

(utils is my custom package for my common classes)

Why does the above line not allow me to do the following

classNameOfMainFunction.randomGen

Am I programming wrong here? Is this even possible.

I basically want to make the class globally and use it anywhere.


Solution

  • A public static field of a public class can be used anywhere, you just need to use the right syntax to access it.

    If you declare:

    package foo;
    
    public class Global {
        public static Some thing;
    }
    

    And do

    import foo.Global;
    

    you can access the field with

    Global.thing
    

    Alternatively, you can do

    import static foo.Global.thing;
    

    and access it with

    thing