my dog learned polymorphism
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes regarding static instance variable Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "regarding static instance variable" Watch "regarding static instance variable" New topic

regarding static instance variable

Prashant Khurpade

Joined: Sep 03, 2008
Posts: 9
hi all,

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

class MyCalss{

static MyClass myClass = new MyClass();

VidyaVikas Yalamanchili

Joined: Nov 26, 2007
Posts: 10

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

with Regards,<br />VidyaVikas Yalamanchili SCJP 5.0
Giovanni De Stefano
Ranch Hand

Joined: Aug 17, 2004
Posts: 154
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!


SCJP 1.4
rajeev jayappa

Joined: Sep 15, 2008
Posts: 8
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

Joined: Aug 17, 2004
Posts: 154
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!

I agree. Here's the link:
subject: regarding static instance variable
jQuery in Action, 3rd edition