• 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:
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

How many ways can we create an object

 
Greenhorn
Posts: 24
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Hi all,
How many ways can we create an object. To my knowledge
1) using new operator
2) using Class.forName(ClassName);
3) using clone method
are these correct, any one I missedout ?
 
Bartender
Posts: 6663
5
MyEclipse IDE Firefox Browser Linux
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

Class.forName(ClassName)



That just loads the class dont it ? You never get a reference to a usable object in the heap. That is... you get a class descriptor that just gives you info about this class.

How about String x = "hello"; ? Objects are created in the pool.
 
author and cow tipper
Posts: 5009
1
Hibernate Spring Tomcat Server
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Could you say, let the JVM create one for you? Isn't that what happens with Java 1.5 autoboxing?



Similary, the new keyword doesn't need to be used with String objects, or when creating arrays. Does that count?

Isn't 'using a clone method' the same as say, using a 'factory' method? After all, isn't the JVM just using the new keyword behind the scenes? Philisophical argument I guess.

This is stated purely out of ignorance of the API, but can you do something funky with reflection as well? Just a thought.

-Cameron McKenzie
 
(instanceof Sidekick)
Posts: 8791
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Reading from an object stream might count as another way.

Yes, reflection is another option. class.forName().newInstance() only invokes no-args constructors. For other constructors you have to dig deeper into reflection.

Did we just do some homework?
 
reply
    Bookmark Topic Watch Topic
  • New Topic