Win a copy of Think Java: How to Think Like a Computer Scientist this week in the Java in General forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Instantiating diff types

 
aakash bhatt
Ranch Hand
Posts: 182
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
What is the diff between these 3 invocation types
1) Cal a = new Cal();
2) Cal a = Cal.getInstance();
3)Class c = Class.forName("java.lang.String");
 
Joel McNary
Bartender
Posts: 1840
Eclipse IDE Java Ruby
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Two and Three are essentially the same: You are using some sort of Factory to return the desired instance. In the latter case, you are specifying a parameter to the Factory indicating what instance you want. In the former case, youare just requesting the default instance. (This could be a Singleton instance or some other algorithm to define the a default instance, such as in the case of the java.util.Calendar class upon which this example seems to be based, an instance of the correct (locale-based) subclass of Calendar initialized to today's date).
The First example is merely an object creation; it does nothing special other than create an object and call the constructor.
 
Bear Bibeault
Author and ninkuma
Marshal
Pie
Posts: 64830
86
IntelliJ IDE Java jQuery Mac Mac OS X
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Two and Three are essentially the same:

Not quite.
In 2, a static factory method has been defined for Cal which returns an object which may or may not have been newly created.
In 3, a Class representing the Cal class is loaded and returned. No Cal instance is created.
hth,
bear
[ July 15, 2003: Message edited by: Bear Bibeault ]
 
Marilyn de Queiroz
Sheriff
Posts: 9063
12
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
1) Cal a = new Cal();

The most direct way to instantiate a class

2) Cal a = Cal.getInstance();

This method is specific to certain classes, GregorianCalendar being one of them. This won't work for all classes.

3) Class c = Class.forName("java.util.Date");

A highly dynamic way of instantiating a class by using reflection. Sometimes you have to add the newInstance() method on the end.

Date d = Class.forName("java.util.Date").newInstance();
(Thanks, Joel)
[ July 15, 2003: Message edited by: Marilyn de Queiroz ]
 
Joel McNary
Bartender
Posts: 1840
Eclipse IDE Java Ruby
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Originally posted by Bear Bibeault:

Not quite.
[ July 15, 2003: Message edited by: Bear Bibeault ]

True, but I wan't referring to the results when I said they were essentailly the same, but rather to the process/architecture used to acheive those results.
And Example three results in the java.lang.String.class object, not the Cal.class object
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic