Lemex
Lemex

Reputation: 3794

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.

Upvotes: 0

Views: 226

Answers (2)

meriton
meriton

Reputation: 70574

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

Upvotes: 2

djechlin
djechlin

Reputation: 60788

About the best you can get is this:

public abstract class GloballyUsed {
    public static int method() { return 4; 
    /* determined by fair
     * dice roll, guaranteed to be random */
    }

and:

GloballyUsed.method();

to call elsewhere.

Note per comment (I just learned this) since Java 5 you can import just a specific method name as:

import static {package}.GloballyUsed.method;

Note I added the keyword abstract, this is to further convince you that you never actually instantiate GloballyUsed. It has no instances. You probably have some reading to do on what static means.

Upvotes: 2

Related Questions