由clone引出的 protected 问题

深拷贝和浅拷贝中,实现clone()的第二点,是要重写 Object()类的clone()方法,并将protected改为public。
如果不重写行吗? 因为Object 类的clone() 方法是protected修饰的, 我原来对protected的理解为 : "同一个包或者不同包的子类可以访问"

package com.nemo.lang.clone;

public class Person implements Cloneable {
    

}
package com.nemo.lang.clone;

public class TestClone {
    public static void main(String[] args) throws CloneNotSupportedException {
        Person person = new Person();
        person.clone();// Compile error (The method clone() from the type Object is not visible)
        
        Object object = new Object();
        object.clone(); //Compile error (The method clone() from the type Object is not visible) 
              //当 Person 类没有重写clone()方法时 ,object.clone() 和 person.clone()它们是一样的,都是调用Object 的clone()方法。
} }

 Object类是所有类的父类,那么为什么子类不能访问父类的protected修饰的方法呢?

 

"与基类不在同一个包中的子类,只能访问自身从基类继承而来的受保护成员,而不能访问基类实例本身的受保护成员"

protected 修饰的类和属性,在同一个包或者不同包的子类可以访问,可以理解为 : 

 

在不同包时,指的是通过自身实例(自身的引用)访问,而不能通过父类实例(引用)访问。

在相同包时,protected和public是一样的。注意(Object类和TestClone可不是同一个包)

 

public class Person  implements Cloneable {
    public static void main(String[] args) throws CloneNotSupportedException {
        Person person = new Person();
        person.clone(); // Compile successful
    }
}
package com.nemo.lang.clone;

public class TestClone {
    public static void main(String[] args) throws CloneNotSupportedException {
        TestClone testClone = new TestClone();
        testClone.clone(); //Compile successful
    }
}

(

  试了一堆例子,难道只有我从一开始就理解错了?

  查了一些资料

  http://blog.csdn.net/ciawow/article/details/8262609

)

posted @ 2014-03-31 16:40  廖东海  阅读(935)  评论(0编辑  收藏  举报