• Post Reply Bookmark Topic Watch Topic
  • New Topic

newInstance()  RSS feed

 
Michelle Joe
Greenhorn
Posts: 11
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
can anyone tell me the difference between line 1 and line 2:
static ClassA instance;
// ClassB implements ClassA
instance = (ClassA) new ClassB(); // line 1
instance = (ClassA) Class.forName(ClassB).newInstance(); // line 2

As java api specification stated that newInstance() is to create a new instance of the class represented by this Class object, then i assume there is no difference using "new" keyword to create a new instance of a class. Pls correct me if i am wrong.
 
Joe Ess
Bartender
Posts: 9439
12
Linux Mac OS X Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You are correct in saying that the end result is the same, an instance of ClassB is created. The reason for the apparent duplication of functionality is that "Class.forName(SomeClassName).newInstance()" gives one the ability to specify the class being created at runtime. Check out the Java Tutorial trail on Reflection for more information on what can be done with a Class.
If the name of the class is not determined at runtime, the "new" keyword is the preferred way to create a new instance.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!