简体   繁体   English

Java 中关于 clone() 、 Object 类和 Clonable Interface 的混淆

[英]confusion regarding clone() , Object class and Clonable Interface in Java

If clone() is a part of the Object class , then why do we need to implement Clonable interface to use clone() ?如果clone()Object类的一部分,那么为什么我们需要实现Clonable接口来使用clone()

I have read that clone() is protected member of Object , then what is the relationship between clone() and Clonable interface.我已经读过clone()Object受保护成员,那么clone()Clonable接口之间的关系是什么。 Sorry if I sound stupid.对不起,如果我听起来很愚蠢。 I have just began learning Java.我刚刚开始学习Java。

Cloneable is a marker interface. Cloneable是一个标记界面。 It doesn't have any methods.它没有任何方法。 Just to whitelist your class to make Cloneable只是为了将您的班级列入白名单以使其可克隆

From docs来自文档

A class implements the Cloneable interface to indicate to the Object.clone() method that it is legal for that method to make a field-for-field copy of instances of that class.一个类实现了 Cloneable 接口,以向 Object.clone() 方法指示该方法制作该类实例的字段对字段副本是合法的。 Invoking Object's clone method on an instance that does not implement the Cloneable interface results in the exception CloneNotSupportedException being thrown.在未实现 Cloneable 接口的实例上调用 Object 的 clone 方法会导致抛出异常 CloneNotSupportedException。

It is highly not recommended to use clone().强烈不建议使用 clone()。 I won't go into depth as this off topic but if you need more data on this please check Effective Java. Read Item 11: "Override clone judiciously"我不会深入探讨这个题外话,但如果您需要更多关于此的数据,请查看Effective Java. Read Item 11: "Override clone judiciously" Effective Java. Read Item 11: "Override clone judiciously" . Effective Java. Read Item 11: "Override clone judiciously"

Object.clone() has an implementation. Object.clone()有一个实现。 It makes a shallow copy of the object if the object implements Cloneable.如果对象实现了 Cloneable,它会生成对象的浅拷贝。

The .clone() method does not belongs to any interface. .clone()方法不属于任何接口。

Having a .clone() method and implementing the Cloneable interface are completely different things.拥有.clone()方法和实现Cloneable接口是完全不同的事情。

You only need to implement the Cloneable interface if you intend to make use of Object's clone method如果你打算使用 Object 的 clone 方法,你只需要实现Cloneable接口

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM