java - Why protected method is not accessible from subclass? -
consider 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
subclass of abstractvehicle
contains protected
method speedfactor
. able call method speedfactor
if referenced same class. when super class used reference method speedfactor
not accessible.
what reason hiding method?
your sedancar
class in different package abstractvehicle
class. protected
methods can accessed same package or subclasses.
in case of sedancar
:
sedancar sedan = new sedancar(); sedan.speedfactor();
you calling protected
method same package: ok. sedancar
in package car
, main()
method in class in package car
(actually same class).
in case of abstractvehicle
:
abstractvehicle vehicle = new sedancar(); vehicle.speedfactor();
you try call protected
method package: not ok. main()
method try call in package car
while abstractvehicle
in package vehicle
.
basically understand this:
you have variable of type abstractvehicle
declared in package (vehicle
). may or may not hold dynamic type of sedancar
. in case does, hold instance of other subclass defined in package, e.g. in sportcar
. , since in package car
(the main()
method), not allowed invoke vehicle.speedfactor()
(which protected abstractvehicle.speedfactor()
).
Comments
Post a Comment