File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes getInstance() 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 "getInstance()" Watch "getInstance()" New topic


sethu chiyan

Joined: Apr 05, 2005
Posts: 10

Can u exaplain bit about getInstance,
when do we need to use???

Calendar _calendar = Calendar.getInstance();// y do v use here

explain with more information.

Mark Spritzler

Joined: Feb 05, 2001
Posts: 17276

getInstance is usually a method that you have in a "Factory" class. There is a design pattern that is called "Factory Method" pattern, which has a factory class that returns instances of a class. Instead of creating the class through "new", you go through the Factory and call its getInstance() method.

There are many reasons to use this design pattern and a discussion like that, I am sure you can find in our UML/Design Patterns forum. Just do a search in that forum for Factory.


Perfect World Programming, LLC - iOS Apps
How to Ask Questions the Smart Way FAQ
Mark Spritzler

Joined: Feb 05, 2001
Posts: 17276

Also used in the Singleton pattern as well.

Jeff Jetton
Ranch Hand

Joined: Mar 29, 2005
Posts: 71
Just to add to what's already been said, here's why you need to use getInstance with a Calendar object.

If you look up the documentation for the Calendar class, you'll notice that its constructors have the "protected" access modifier. In other words, no code that lies outside of its package (the "java.*" package) can call the constructor. And if you can't call the constructor, you can't use "new" to create a new instance of the object.

So how do you get a new instance if you can't call the constructor? You call a static, class method--in this case, that's getInstance(). That method is allowed to call the constructor, since it's part of the same class. It then passes a reference to the new object back to you.

A class is typically set up this way when a central point of control over the creation of the object is needed for some reason. For example, the class might look around to see if the object has already been created. If it has, it will just pass you a reference to that already-existing instance. If not, it will create one for you. (That's example of the "Singleton" pattern Mark mentioned, by the way.)

- Jeff
Parameswaran Thangavel
Ranch Hand

Joined: Mar 01, 2005
Posts: 485
hi jeff
is this object eligible for GC
nagaraj reddy
Ranch Hand

Joined: Feb 21, 2005
Posts: 43
Please anybody explain singleton pattern where there is a private constructor and we need get the instance through the getInstance() method
I agree. Here's the link:
subject: getInstance()
It's not a secret anymore!