Win a copy of The Java Performance Companion this week in the Performance forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

regarding static instance variable

 
Prashant Khurpade
Greenhorn
Posts: 9
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
hi all,

what is use of creating static instance of a class, say

class MyCalss{

static MyClass myClass = new MyClass();

}
 
VidyaVikas Yalamanchili
Greenhorn
Posts: 10
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
HI,

Creating a Static Referance of a Class used in Singleton.In singleton you The class constructor will be of private.When constructor is private you cant directly create a instance you need to have a static method to ctreate a instance instance variables cant be used in static methods so we use static instance varible to create the class.

I think you got it
 
Giovanni De Stefano
Ranch Hand
Posts: 161
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hello Prashant,

I would say the main (maybe only reason) is to implement the Singleton Pattern: see here for more details.

Basically you want one and only one instance of a particular class and any client code to that class must use that single instance.

I used to use Singletons to create some kind of managers (ThemeManagers, PropertyManager etc.) because I never liked a bunch of static methods in one helper/manager class.

Here is a very simple example of a Singleton:



The client code would never do new PropertyManager() but would simply call the manager with something like:



I hope this helps!

Giovanni
 
rajeev jayappa
Greenhorn
Posts: 8
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
i think we need to check whether the instance is null then only
we have to create a new static instance is that right for
a singleton??
 
Giovanni De Stefano
Ranch Hand
Posts: 161
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hello Rajeev,

it depends on what your constructor does: if the constructor opens a file or worse connects to a DB or does anything that might go wrong, then yes, you have to check if the INSTANCE is null or not (and catch any exception) and if it is you should fall back to a default (sometimes dummy) alternative.

If you are not doing anything critical then I always felt comfortable skipping that check.

In my experience, with a PropertyManager Singleton, I usually had to read te properties from a file, but if the file was not there, I never returned null but instead I logged the issue and used a default PropertyManager with default values.

I believe this brings more robust code and it is a neater design.

Just my 2 cents!

Giovanni
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic