从java.lang.Object访问clone() [英] Accessing clone() from java.lang.Object

查看:87
本文介绍了从java.lang.Object访问clone()的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我无法理解的。

java.lang.Object clone()使用 protected 修饰符定义。根据定义,它可以通过名称在其自己的类定义中访问,通过名称在从它派生的任何类中,以及在同一包中任何类的定义中的名称。

In java.lang.Object the clone() is defined with protected modifier. By definition than it can be accessed by name inside its own class definition, by name inside any class derived from it, and by name in the definition of any class in the same package.

此处 Sample 类位于另一个包中,显然它无法访问 clone() 对象类。但是当 Sample Object 隐式派生时,为什么它无法访问它?该定义并未说明它必须满足两个条件(在同一个包内并且也是一个子类)。

Here the Sample class is in another package, and obviously it can't access clone() from the Object class. But as Sample derives implicitly from Object, why is it not able to access it? The definition doesn't say that it HAS to satisfy both conditions (inside same package AND also to be a subclass).

public class Sample {

  public Object foo() throws CloneNotSupportedException {
   ... 
   return someObject.clone();
  }
}


推荐答案

In在你的情况下, clone()方法是不可见的,因为你没有从子类中调用它。 示例派生自 Object ,因此它可以访问自己的 clone()方法,但不是其他对象的方法。

In your case, the clone() method is not visible because you are not calling it from a subclass. Sample derives from Object, so it can access its own clone() method, but not that of other objects.

对象 clone()设计有多个错误。所以使用它并不是一个好习惯 - 很难做到正确:

Object clone() was designed with several mistakes. So it is not a good practice to use it - it is very hard to get it right:


  • 假设不是每个对象都是默认情况下可克隆

  • 如果覆盖 clone()将其公开,它仍然会失败,因为每个类都必须实现 Cloneable

  • Cloneable 但是,没有定义任何方法,因此用户对象不能将其称为 Cloneable 并期望克隆方法。

  • 层次结构中的每个类都必须调用 super.clone()使默认克隆机制起作用

  • the assumption is that not every object is clonable by default
  • if you override clone() making it public, it will still fail, because each class has to implement Cloneable
  • Cloneable, however, does not define any methods, so the users of the objects can't refer to it as Cloneable and expect a clone method.
  • every class in a hierarchy must call super.clone() for the default cloning mechanism to work

检查这个问题替代方案。

这篇关于从java.lang.Object访问clone()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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