访问权限

private : 同类
default : 同类 \ 同包(路径)
protected : 同类 \ 同包(路径)\ 子类(作为子类只能调用自己的父类而不能调用别的父类的方法,即使两个父类相同)
public : 公共

//测试 protected 对象作为子类去调用父类方法
public class ObjectAccess1 {

    public static void main(String[] args) {
        //已知:所有new的对象 都是Object类的子类
        //Object类中有protected方法clone()
        Person person = new Person();

        person.clone();  //调用失败 无权限
        //'clone()' has protected access in 'java.lang.Object'
        //报错说明作为子类对象的person不能访问父类protected的方法clone() why?
        //谁访问?  ObjectAccess1 作为子类super访问父类 java.lang.Object
        //访问谁?  Person类型的对象 作为子类super访问父类 java.lang.Object(clone)
        //也就是说  ObjectAccess1类内部对 Object类的方法进行调用,调用的是ObjectAccess1的父类
        //而 Person类型的对象 只能访问 Person的父类
        //ObjectAccess1 与 Person 有同一个父类,
        //但Person类型的对象不能在ObjectAccess1中访问到Person的父类,相反只能访问到ObjectAccess1的父类,必然失败
        //在Person类中可以以person对象对Person的父类Object中受保护的方法进行调用
        //在ObjectAccess1类中只有ObjectAccess1类型的对象能够调用父类Object中受保护的方法

    }

}

class Person{
    void test() throws Exception{
        clone();      //调用父类protected方法成功
    }
}
posted @ 2023-01-02 13:50  LaViez  阅读(30)  评论(0)    收藏  举报