访问修饰符protected

来源:互联网 发布:windows找不到cdm 编辑:程序博客网 时间:2024/05/22 04:25

protected修饰符的确让我有点困惑。例如:Object的clone()方法就是protected修饰的。发现,有的时候可以访问,但很多时候根本访问不到。
(一)下面就以clone()方法为例
这里写图片描述
我在SuperClass类中,不重写clone(),只是访问。代码如下:

package cn;public class SuperClass implements Cloneable{    public static void main(String[] args) throws CloneNotSupportedException {        SuperClass s=new SuperClass();        Object clone = s.clone();//子类可以访问父类的protected方法    }}

现在让SubClass继承SuperClass。
这里写图片描述

package cn;public class SubClass extends SuperClass {    public static void main(String[] args) {        SuperClass sup=new SuperClass();        //因为在SuperClass类中并没有覆盖clone(),所以在SubClass类中看不到clone()        sup.clone();//在这里是访问不到sup的clone方法的,编译出错    }}

可见,除了在SuperClass类的内部,其它地方无法访问它的clone方法。
(二)要想调用对象的clone方法,该怎么做呢?

在一个类的内部,我们总是可以访问它的clone(),实现对象的克隆。但是大部分情况下,我们都是在类外进行克隆的。

我们可以重写Object的clone(),并把访问修饰符改为public(如果不改的话,访问修饰符就是protected,并不能达到“在任何地方都能实现clone”的目的)。
这里写图片描述

有2种情况可以访问到protected方法:1)A类和B类在同一个包下,那么A类可以访问B类的protected方法;2)子类可以访问父类的protected方法

(1)同一个包下的类,可以访问protected方法

package cn;public class Parent1 {    protected void protected_method(){//定义一个protected方法        System.out.println("protected");    }}
package cn;public class Parent2 {    public static void main(String[] args) {        Parent1 p1=new Parent1();        //Parent1类和Parent2类在同一个包下,可以访问Parent1的protected方法        p1.protected_method();    }}
package com;import cn.Parent1;public class Parent3 extends Child1{    public static void main(String[] args) {        Parent1 p1=new Parent1();        //Parent1类和Parent3类不在同一个包下,无法访问Parent1的protected方法        p1.protected_method();//编译出错    }}

(2)子类可以访问父类的protected方法(即便子类和父类不在同一个包下面)
通过子类去访问父类的protected方法,并且子类可以重写(覆盖)父类的protected方法。

package cn;public class Parent1 {    protected void protected_method(){//定义一个protected方法        System.out.println("protected");    }}
package com;import cn.Parent1;public class Child1 extends Parent1{    public static void main(String[] args) {        Child1 c1=new Child1();        //子类和父类不在同一个包下        c1.protected_method();//通过子类去访问父类的protected方法    }}
原创粉丝点击