• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Tim Cooke
  • Campbell Ritchie
  • paul wheaton
  • Ron McLeod
  • Devaka Cooray
Sheriffs:
  • Jeanne Boyarsky
  • Liutauras Vilda
  • Paul Clapham
Saloon Keepers:
  • Tim Holloway
  • Carey Brown
  • Piet Souris
Bartenders:

newInstance()

 
Greenhorn
Posts: 11
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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.
 
Bartender
Posts: 9626
16
Mac OS X Linux Windows
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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.
 
reply
    Bookmark Topic Watch Topic
  • New Topic