【问题标题】:overriding clone method but it is still protected覆盖克隆方法,但它仍然受到保护
【发布时间】:2019-09-26 16:10:16
【问题描述】:
public Object clone() throws CloneNotSupportedException {
DoublyLinkedList<E> other=(DoublyLinkedList<E>) super.clone();
if(size > 0){
  other.header=new Node<>(null,null,null);
  other.trailer=new Node<>(null,other.header,null);
  other.header.setNext(other.trailer);
  Node<E> walk=header.getNext();
  Node<E> otherWalk=other.header;
  while (walk != trailer){
    Node<E> newest=new Node<> 
 (walk.getElement(),otherWalk,otherWalk.getNext());
    otherWalk.setNext(newest);
    walk=walk.getNext();
    otherWalk=otherWalk.getNext();
  }
  }
 return other;
 }

我将 clone 方法重写为 public 并在我的代码中使用它。

public Object deepCopy() {
Node<E> walk = header;
while (walk != trailer) {
  Node<E> newNode = new Node<E>((E)
          (walk.getElement()).clone(), null, null);
  ......

但它有一个错误提示“clone() 在 java.lang.Object 中具有受保护的访问权限”。

我已经在我的班级中将 clone 方法更改为 public,为什么它仍然受到保护?

【问题讨论】:

  • 不明白。您要克隆哪个类?

标签: java clone overwrite


【解决方案1】:

当您尝试像以前那样调用克隆方法时:

(E)(walk.getElement()).clone()

它尝试调用Object 类中定义的clone 方法,然后尝试将克隆转换为E 类型。但它失败了,因为Object#clone 方法具有受保护的范围。

为了调用被覆盖的 clone 方法,你必须这样写:

(E)((E)(walk.getElement().clone()))

【讨论】:

  • 感谢您的回答。我不明白这是一个对象类方法,我的第一个和第二个代码在同一个类中,所以我的克隆方法是最后更新的部分。为什么不使用?我认为这很奇怪。你也能解释一下你的第二个代码的两次转换吗?比如 walk.getElement().clone() 返回一个对象,为什么要强制转换两次?
猜你喜欢
  • 2013-07-01
  • 2011-08-04
  • 2015-10-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-07-08
  • 2011-01-20
  • 2012-05-14
相关资源
最近更新 更多