Java 继承访问权限protected

Java 继承访问权限protected,变量和函数有public/private修饰符,public表示外部可以访问,private表示只能内部使用,还有一种可见性介于中间的修饰符protected,表示虽然不能被外部任意访问,但可被子类访问。另外,protected还表示可被同一个包中的其他类访问,不管其他类是不是该类的子类。我们来看个例子,这是基类代码:

public class Base {
    protected   int currentStep;
    protected void step1(){
    }
    protected void step2(){
    }
    public void action(){
        this.currentStep = 1;
        step1();
        this.currentStep = 2;
        step2();
    }
}

action表示对外提供的行为,内部有两个步骤step1()和step2(),使用currentStep变量表示当前进行到了哪个步骤,step1()、step2()和currentStep是protected的,子类一般不重写action,而只重写step1和step2,同时,子类可以直接访问currentStep查看进行到了哪一步。子类的代码是:

public class Child extends Base {
    protected void step1(){
        System.out.println("child step " + this.currentStep);
    }
    protected void step2(){
        System.out.println("child step " + this.currentStep);
    }
}

使用Child的代码是:

public static void main(String[] args){
    Child c = new Child();
    c.action();
}

输出为:
Java 继承访问权限protected

基类定义了表示对外行为的方法action,并定义了可以被子类重写的两个步骤step1()和step2(),以及被子类查看的变量currentStep,子类通过重写protected方法step1()和step2()来修改对外的行为。

这种思路和设计是一种设计模式,称之为模板方法。action方法就是一个模板方法,它定义了实现的模板,而具体实现则由子类提供。模板方法在很多框架中有广泛的应用,这是使用protected的一种常见场景。

酷客教程相关文章:

赞(0)

评论 抢沙发

评论前必须登录!