0

Possible Duplicate:
What are all the different ways to create an object in Java?

How many ways to create an object in java? I was asked about this in a recent interview.

Since everything in Java is on the heap, I would think 'new' is the way to go. Comments?

Community
  • 1
  • 1
Neel
  • 9,913
  • 16
  • 52
  • 74
  • Possible duplicate of http://stackoverflow.com/questions/95419/what-are-all-the-different-ways-to-create-an-object-in-java – Piyush Mattoo Mar 20 '11 at 18:57
  • Take a look at: http://www.geekinterview.com/question_details/22478 answer from jkathiravan – Adnan Mar 20 '11 at 19:00

2 Answers2

2

4 ways off the top of my head(I know this because I too was asked this question once!):

Using new:

Car obj = new Car();

By Cloning:

Car a = new Car();
Car b = a.clone();

Using forName from Class

Car obj = (Car) Class.forName("Car").newInstance();

By Deserializing:

ObjectInputStream in = new ObjectInputStream(instream);
Car object = (Car) in.readObject();
Mike Lewis
  • 63,433
  • 20
  • 141
  • 111
0

new definitely, reflection is another option

javanna
  • 59,145
  • 14
  • 144
  • 125
Jan Zyka
  • 17,460
  • 16
  • 70
  • 118