开发者

A class that only has static data and methods to access these data. How to implement that properly?

I know that is a beginner's question. I'm new to java and and also to programming in general.

Say I got a class that has only static data, example:

class Foo {
private static int x;  }

I want to use the class without instan开发者_开发问答tiating any object. So I want to be able to do:

Foo.setX(5);
Foo.getX();

What is the best way to implement this class, I'm a little bit confused about interfaces and other stuff for now.

Thanks.


Why don't you just define two static methods that modify/return the static field?

Static Methods in Java


I think a Singleton is what your looking for:

  • http://en.wikipedia.org/wiki/Singleton_pattern

The singleton class:

public class Singleton {

    private static final Singleton INSTANCE = new Singleton();

    private int x;

    // Private constructor prevents instantiation from other classes
    private Singleton() {
    }

    public static Singleton getInstance() {
        return INSTANCE;
    }

    public int getX() {
        return x;
    }

    public void setX(int x) {
        this.x = x;
    }

}

And to access from anywhere in your code :

int x = Singleton.getInstance().getX();
Singleton.getInstance().setX(10);


You can just define getX and setX methods as static:

class Foo
{
    private static int x; 

    public static int getX()
    {
        return x;
    }

    public static void setX(int x)
    {
        Foo.x = x;
    }
}

Then you can use this without instantiating any object:

Foo.setX(5);
int val = Foo.getX();

As others have suggested, a Singleton is a cleaner approach, although it will not meet your requirement of not instantiating any object.

http://en.wikipedia.org/wiki/Singleton_pattern


You can always have static public methods Get and Set to do what you want. But have a look again, Singleton Pattern may be what you want.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜