Consider the following code snippets:
package vehicle;
public abstract class AbstractVehicle {
protected int speedFactor() {
return 5;
}
}
pack
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()
).