问题
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 instantiating 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.
回答1:
Why don't you just define two static methods that modify/return the static field?
Static Methods in Java
回答2:
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);
回答3:
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
回答4:
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.
来源:https://stackoverflow.com/questions/3966845/a-class-that-only-has-static-data-and-methods-to-access-these-data-how-to-imple