Object creation in Java [duplicate]
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?
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();
new
definitely, reflection is another option
精彩评论