• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Using getInstance() and newInstance() methods

 
Rajdeep Biswas
Ranch Hand
Posts: 221
1
Eclipse IDE Java Opera
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Where and how to use those methods correctly? Why not constructors?

Thanks a million
 
Koen Aerts
Ranch Hand
Posts: 344
Java Linux Oracle
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The where and how depends on the specific class you're trying to use. For instance for a Calendar you would use Calendar.getInstance(). As to the why, have a look at the following: http://en.wikipedia.org/wiki/Factory_method_pattern
 
Winston Gutkowski
Bartender
Pie
Posts: 10509
64
Eclipse IDE Hibernate Ubuntu
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Rajdeep Biswas wrote:Where and how to use those methods correctly? Why not constructors?

Other than Koen's link, Effective Java also has a very good section on using factories.

Just a few reasons for using factories are:
1. The method has a meaningful name.
2. A factory doesn't necessarily have to return you a new object.
3. A factory doesn't even have to return you an object of the specified type. It can, for example, return you an anonymous subclass (sometimes very useful).

Winston
 
It is sorta covered in the JavaRanch Style Guide.
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic