为什么不能从子类访问受保护的方法? [英] Why protected method is not accessible from subclass?

查看:108
本文介绍了为什么不能从子类访问受保护的方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

请考虑以下代码段:

package vehicle;

public abstract class AbstractVehicle {
    protected int speedFactor() {
        return 5;
    }
}

package car;

import vehicle.AbstractVehicle;

public class SedanCar extends AbstractVehicle {
    public static void main(String[] args) {
        SedanCar sedan = new SedanCar();
        sedan
                .speedFactor();
        AbstractVehicle vehicle = new SedanCar();
        // vehicle //WON'T compile
        // .speedFactor();
    }
}

SedanCarAbstractVehicle的子类,其中包含protected方法speedFactor.如果同一个类引用了方法speedFactor,则可以调用该方法.当超类用于引用时,方法speedFactor不可访问.

SedanCar is a subclass of AbstractVehicle which contains a protected method speedFactor. I am able to call the method speedFactor if it is referenced by the same class. When the super class is used for reference the method speedFactor is not accessible.

隐藏该方法的原因是什么?

What is reason for hiding the method?

推荐答案

您的SedanCar类与AbstractVehicle类位于不同的包中.只能从相同包或子类中访问protected方法.

Your SedanCar class is in a different package than the AbstractVehicle class. protected methods can only be accessed from the same package or from subclasses.

对于SedanCar:

SedanCar sedan = new SedanCar();
sedan.speedFactor();

您正在从同一包中调用protected方法:确定. SedanCar在程序包car中,并且main()方法在程序包car中的一个类中(实际上是同一类).

You are calling a protected method from the same package: OK. SedanCar is in package car and main() method is in a class which is in package car (actually the same class).

对于AbstractVehicle:

AbstractVehicle vehicle = new SedanCar();
vehicle.speedFactor();

您尝试调用protected方法,但是从另一个包中调用:NOT OK.尝试调用它的main()方法在程序包car中,而AbstractVehicle在程序包vehicle中.

You try to call a protected method but from another package: NOT OK. The main() method from which you try to call it is in package car while AbstractVehicle is in package vehicle.

基本理解这一点:

您有一个AbstractVehicle类型的变量,该变量在另一个包(vehicle)中声明.它可能包含动态类型SedanCar,也可能不包含.就您而言,它确实可以,但是它也可以包含另一个包中定义的任何其他子类的实例,例如在sportcar中.而且,由于您在程序包car中(main()方法),因此不允许您调用vehicle.speedFactor()(它是受保护的AbstractVehicle.speedFactor()).

You have a variable of type AbstractVehicle which is declared in another package (vehicle). It may or may not hold a dynamic type of SedanCar. In your case it does, but it could also hold an instance of any other subclass defined in another package, e.g. in sportcar. And since you are in package car (the main() method), you are not allowed to invoke vehicle.speedFactor() (which is the protected AbstractVehicle.speedFactor()).

这篇关于为什么不能从子类访问受保护的方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆