Granny's Programming Pearls
"inside of every large program is a small program struggling to get out"
JavaRanch.com/granny.jsp
The moose likes Java in General and the fly likes How many ways can we create an object Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of OCM Java EE 6 Enterprise Architect Exam Guide this week in the OCMJEA forum!
JavaRanch » Java Forums » Java » Java in General
Bookmark "How many ways can we create an object" Watch "How many ways can we create an object" New topic
Author

How many ways can we create an object

Pandu Rangam
Greenhorn

Joined: Dec 08, 2006
Posts: 24
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 ?


SCJP 1.4,<br />SCWCD 1.4
Deepak Bala
Bartender

Joined: Feb 24, 2006
Posts: 6661
    
    5

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.


SCJP 6 articles - SCJP 5/6 mock exams - More SCJP Mocks
Cameron Wallace McKenzie
author and cow tipper
Saloon Keeper

Joined: Aug 26, 2006
Posts: 4968
    
    1

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

Joined: Jan 29, 2003
Posts: 8791
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?


A good question is never answered. It is not a bolt to be tightened into place but a seed to be planted and to bear more seed toward the hope of greening the landscape of the idea. John Ciardi
 
With a little knowledge, a cast iron skillet is non-stick and lasts a lifetime.
 
subject: How many ways can we create an object