Why protected method is not accessible from subclass?

后端 未结 5 1350
我在风中等你
我在风中等你 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:44

    Back in my SCJP for Java 1.5 days, one thing that I used to remember was be wary of superclass reference variables. It isn't quite as surprising to see this now and one thing why this gets confusing is the rule is protected is visible to subclass or same package. What if it's both subclass and different package?

    If you create another package, and do

    package yetAnotherPackage;
    
    import car.SedanCar;
    
    public class Main {
    
        public static void main(String[] args) {
            new SedanCar().speedFactor();
        }
    
    }
    

    you'll see that

    The method speedFactor() from the type AbstractVehicle is not visible
    

    Looks like the rule just propagates. As long as you have a subclass and try to access the protected method within the package of the subclass (or if no subclass, then the package of the parent), you should be good.

提交回复
热议问题