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

How many ways can we create an object

 
Pandu Rangam
Greenhorn
Posts: 24
  • Mark post as helpful
  • send pies
  • 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 ?
 
Deepak Bala
Bartender
Posts: 6663
5
Firefox Browser Linux MyEclipse IDE
  • Mark post as helpful
  • send pies
  • 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.
 
Cameron Wallace McKenzie
author and cow tipper
Saloon Keeper
Posts: 4968
1
Hibernate Spring Tomcat Server
  • Mark post as helpful
  • send pies
  • 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
 
Stan James
(instanceof Sidekick)
Ranch Hand
Posts: 8791
  • Mark post as helpful
  • send pies
  • 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?
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic