wood burning stoves*
The moose likes Java in General and the fly likes Difference between singleton and static class  ? Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Android Security Essentials Live Lessons this week in the Android forum!
JavaRanch » Java Forums » Java » Java in General
Bookmark "Difference between singleton and static class  ?" Watch "Difference between singleton and static class  ?" New topic
Author

Difference between singleton and static class ?

Praveen Kumar
Ranch Hand

Joined: Nov 06, 2006
Posts: 133


Please tell me what are the difference and when i need to go for singleton and static class ?
fred rosenberger
lowercase baba
Bartender

Joined: Oct 02, 2003
Posts: 11169
    
  16

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.


There are only two hard things in computer science: cache invalidation, naming things, and off-by-one errors
Campbell Ritchie
Sheriff

Joined: Oct 13, 2005
Posts: 38057
    
  22
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

Joined: Nov 06, 2006
Posts: 133
Sorry ... I mean

Class X {


public static X getInstance() {

returns X;

}



Jesper de Jong
Java Cowboy
Saloon Keeper

Joined: Aug 16, 2005
Posts: 14074
    
  16

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.


Java Beginners FAQ - JavaRanch SCJP FAQ - The Java Tutorial - Java SE 7 API documentation
Scala Notes - My blog about Scala
fred rosenberger
lowercase baba
Bartender

Joined: Oct 02, 2003
Posts: 11169
    
  16

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.
 
 
subject: Difference between singleton and static class ?
 
Similar Threads
Singleton Object
2 different types of singleton
singleton vs static
Synchronization
difference between the singleton pattern class and static class