为什么不能从子类访问受保护的方法? [英] Why protected method is not accessible from subclass?
问题描述
请考虑以下代码段:
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();
}
}
SedanCar
是AbstractVehicle
的子类,其中包含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屋!