java protected

作者: 砺豪 | 来源:发表于2017-01-22 22:05 被阅读22次
包结构 world 代表any class

stackoverflow

同包可以随便用

package xyy.test.protected_test.pkg1;

/**
 * Created by xyy on 17-1-22.
 */
public class Cookie {
    protected void say(){
        System.out.println("hello");
    }
}
package xyy.test.protected_test.pkg1;

/**
 * Created by xyy on 17-1-22.
 */
public class CookieTest {

    public static void main(String[] args) {
        // 同包可以。
        new Cookie().say();
    }
}

不同包

“在Object类中,clone方法被声明为protected,因此无法直接调用anObject.clone()。子类只能直接调用受保护的clone方法克隆它自己。为此,必须重新定义clone方法,并将它声明为public,这样才能让所有的方法克隆对象”

需要实现Cloneable接口才能clone

package xyy.test.protected_test.pkg2;

import xyy.test.protected_test.pkg1.Cookie;

/**
 * Created by xyy on 17-1-22.
 */
/**
 * 需要支持Cloneable接口才能clone
 */
public class TestCookie extends Cookie implements Cloneable {

    private String name;

    public TestCookie(String name) {
        this.name = name;
    }

    public void test() {
        say();
    }

    @Override
    public Object clone() throws CloneNotSupportedException {
        return super.clone();
    }

    public static void main(String[] args) throws CloneNotSupportedException {

        // -----------比较以下两种---------------

        // new Cookie().say();// error  不同包只能通过继承得到,直接调用是不可见的。

        new TestCookie("test0").say();// 子类不同包,是通过继承得到的,可以

        // -----------比较以下两种---------------
        TestCookie test1 = new TestCookie("test1");
        test1.test();
        TestCookie test2 = (TestCookie) test1.clone();
        test2.test();

        // 验证两个对象是不同引用
        System.out.println(test1 == test2);
    }
}

相关文章

网友评论

    本文标题:java protected

    本文链接:https://www.haomeiwen.com/subject/cmiobttx.html