EDIT: I want the difference between singleton class and a class with only static members. I don't want to compare the singleton class with the static inner class, because java doesn't allow static classes rather than static inner classes.
A Singleton class allows user to have only one object for that class. By this we can restrict the user to have only one instance of the attributes.
This could be achieved by using a class which has only static members and static methods (Not a static inner class)
So, What is the Difference between the following 2 classes
Singleton class:
public class Test {
public static void main(String args[]) {
Singleton s = Singleton.getInstance();
s.foo();
}
}
class Singleton {
private static Singleton obj = new Singleton();
private Singleton() {
}
public static Singleton getInstance() {
return obj;
}
public void foo() {
// something...
}
}
class with only static methods and members:
public class Test {
public static void main(String args[]) {
NotSingleton.foo();
}
}
class NotSingleton {
public static void foo() {
// something...
}
}