Consider the following code snippets:
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
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?
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()
).