开发者

Object creation in Java [duplicate]

开发者 https://www.devze.com 2023-02-19 01:25 出处:网络
This question already has answers here: 开发者_运维技巧 Closed 11 years ago. Possible Duplicate: What are all the different ways to create an object in Java?
This question already has answers here: 开发者_运维技巧 Closed 11 years ago.

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

0

精彩评论

暂无评论...
验证码 换一张
取 消