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,563
  • 15
  • 50
  • 72
  • 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
  • 61,841
  • 20
  • 140
  • 111
0

new definitely, reflection is another option

javanna
  • 56,876
  • 13
  • 139
  • 122
Jan Zyka
  • 16,741
  • 16
  • 69
  • 113