Why protected method is not accessible from subclass?

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

    Because protected is visible to the class itself (like private) and its subclass instances. It is not public.

    For example,

    package vehicles;
    
    public abstract class AbstractVehicle {
        protected int speedFactor() {
            return 5;
        }
    
        public int getSpeed() {
            return 10*speedFactor(); //accessing speedFactor() "privately"
        }
    }
    
    package vehicles.cars;
    
    public class SedanCar extends AbstractVehicle {
        @Override
        protected int speedFactor() { //overriding protected method (just to show that you can do that)
            return 10;
        }
    
        @Override
        public int getSpeed() {
            return 20*speedFactor(); //this is part of the instance (!!!) therefore it can access speedFactor() protected method too
        }
    }
    
    package vehicles.main;
    
    public class Main {
        public static void main(String[] args) {
            AbstractVehicle vehicle = new SedanCar();
            int speed = vehicle.getSpeed(); //accessing public method
            vehicle.speedFactor(); //cannot access protected method from outside class (in another package)
        }
    }
    

    The static main() method is not part of the instance, that is why it cannot access the protected method.

提交回复
热议问题