为什么克隆时不执行构造函数 [英] Why constructor is not executed while cloning

查看:170
本文介绍了为什么克隆时不执行构造函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Animal animal = new Animal(101);              //Constructor is executed.

Animal clone=(Animal)animal.clone()     //Constructor is not executed. Why ?


推荐答案

的默认实现clone() Object 类中给出的方法不会调用任何类型的构造函数。

The default implementation of the clone() method given in the Object class does not call any kind of constructor.

它是对象的浅拷贝,因为它通过创建新实例然后通过赋值复制内容来创建Object的副本,这意味着如果你的类包含一个可变字段,然后原始对象和克隆都将引用相同的内部对象

It makes a "shallow copy" of object, because it creates copy of Object by creating new instance and then copying content by assignment, which means if your Class contains a mutable field, then both original object and clone will refer to same internal object.

尝试查看页面。

这篇关于为什么克隆时不执行构造函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆