Why does the compiler give an error message when you reduce the visibility of a method while overriding it in the subclass?
You cannot reduce the visibility of a inherited method. Here parent class has func() method which is public and overridden by the subclass TestClass which is private.
You can not make access modifier more restrictive, because that would violate the basic rule of inheritance that a subclass instance should be replacable in place of a superclass instance.
The ability of a subclass to override a method allows a class to inherit from a superclass whose behavior is "close enough" and then to modify behavior as needed. The overriding method has the same name, number and type of parameters, and return type as the method that it overrides.
Methods a Subclass Cannot Override Also, a subclass cannot override methods that are declared static in the superclass. In other words, a subclass cannot override a class method. See Instance and Class Members for an explanation of class methods.
Because every instance of the subclass still needs to be a valid instance of the base class (see Liskov substitution principle).
If the subclass suddenly has lost one property of the base class (namely a public method for example) then it would no longer be a valid substitute for the base class.
Because if this was allowed, the following situation would be possible:
Class Sub inherits from class Parent. Parent has a public method foo
, Sub makes that method private. Now the following code would compile fine, because the declared type of bar
is Parent:
Parent bar = new Sub(); bar.foo();
However it is not clear how this should behave. One possibility would be to let it cause a runtime error. Another would be to simply allow it, which would make it possible to call a private method from outside, by just casting to the parent class. Neither of those alternatives are acceptable, so it is not allowed.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With