0

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...
    }
}
Venkatesh
  • 1,537
  • 15
  • 28
  • Here: http://stackoverflow.com/questions/519520/difference-between-static-class-and-singleton-pattern – tomloprod Dec 24 '14 at 10:58
  • @Jon Skeet and @ tomloprod, That question compares singleton class with the static inner class. Please check out my edited question. – Venkatesh Dec 24 '14 at 11:58
  • 1
    @Venkatesh: No, it doesn't. It isn't Java-specific. I suspect it's actually more likely to be from a C# background, given the author - and in C#, a static class is a class with only static members. Read my answer on that question, which is specifically about what you're asking. – Jon Skeet Dec 24 '14 at 11:59
  • @JonSkeet Oh.Sry I had interpreted your answer in a different way. Thank you. – Venkatesh Dec 24 '14 at 12:13

0 Answers0