Why protected method is not accessible from subclass?

后端 未结 5 1423
我在风中等你
我在风中等你 2021-02-08 23:04

Consider the following code snippets:

package vehicle;

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

pack         


        
5条回答
  •  不要未来只要你来
    2021-02-08 23:52

    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.

    In case of SedanCar:

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

    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).

    In case of AbstractVehicle:

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

    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.

    Basically understand this:

    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()).

提交回复
热议问题