Win a copy of Mesos in Action this week in the Cloud/Virtualizaton forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Difference between singleton and static class ?

 
Praveen Kumar
Ranch Hand
Posts: 133
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator


Please tell me what are the difference and when i need to go for singleton and static class ?
 
fred rosenberger
lowercase baba
Bartender
Posts: 12125
30
Chrome Java Linux
  • Likes 2
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
They are not even close to the same thing.

A singleton is when you only want to allow and object to be instantiated ONCE. If you need some kind of gatekeeper that everyone talks to, so that all decisions are made by one person. Note: This is probably the most over-used (and possibly mis-used) design pattern.

A static class is used when you don't need ANY objects to be created. The Math class is a classic example. I don't need an actual Math object, I just need to be able to call the methods. There is no state that needs to be saved, so no object is needed.
 
Campbell Ritchie
Sheriff
Pie
Posts: 48968
60
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Is that a static class? I would have called it a utility class.
So what is a static class (apart from a kind of nested class)?
 
Praveen Kumar
Ranch Hand
Posts: 133
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Sorry ... I mean

Class X {


public static X getInstance() {

returns X;

}



 
Jesper de Jong
Java Cowboy
Saloon Keeper
Posts: 15284
39
Android IntelliJ IDE Java Scala Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
That looks like part of how you would implement a singleton in Java.

What do you mean by a "static class"? You cannot make a top-level class static. You can make nested classes static, which means that instances of the nested class don't have a reference to the object of the enclosing class. That, however, doesn't have anything to do with singletons.
 
fred rosenberger
lowercase baba
Bartender
Posts: 12125
30
Chrome Java Linux
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Campbell Ritchie wrote:Is that a static class? I would have called it a utility class.
So what is a static class (apart from a kind of nested class)?

Sorry...I was thinking of the Math class, where all the methods are static. I assumed that's what the OP meant, but I now realize I am probably wrong.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic