1

如果我说

class A{
}

然后它隐式继承 Object 类。所以我的类如下:

class A{

       protected Object clone(){
       }  /// Here i am not overridning
       //All the other methods (toString/wait/notify/notifyAll/getClass)
}

现在为什么我不能访问 Class B 中的 clone() 方法,该方法在 Class A 的同一个包中。

Class B{
       A a = new A();
       a.clone();
       **
}

//** 说克隆在对象类中受到保护。但是我没有访问 Object 的 clone 方法。无论如何,我在这里调用 A 类的 clone 方法,但我还没有重载。

4

2 回答 2

3

protected方法在 中定义java.lang.Object,因此您不能从另一个包中调用它 - 只能从子类中调用。

您在 a 引用上调用它,A但它是 , 的方法java.lang.Object,直到您覆盖它。

覆盖时clone(),您应该将修饰符更改为public并实现Cloneable。但是使用该clone()方法并不是一个好主意,因为它很难正确实现。使用 commons-beanutils 进行浅克隆。

确保区分“覆盖”和“重载”。

于 2010-07-02T09:01:10.000 回答
1

这完美的工作

class A{

       protected Object clone(){
           return this;
       }  
}

public class B{
       public B() {
           A a = new A();
           a.clone();
           System.out.println("success");
       }
       public static void main(String[] args) {
        new B();
    }

}
于 2010-07-02T09:02:23.447 回答