Why can't you reduce the visibility of a method in a Java subclass?

Why does the compiler give an error message when reducing the visibility of a method when overriding it in a subclass?

+41
java override polymorphism subclassing
Oct 21 '09 at 12:58
source share
3 answers

Since each instance of the subclass must still be a valid instance of the base class (see the Liskov substitution principle ).

If a subclass suddenly lost one property of the base class (for example, a public method, for example), then it will no longer be a valid replacement for the base class.

+65
Oct 21 '09 at 12:59
source share

Because, if allowed, the following situation is possible:

The Sub class inherits from the Parent class. The parent has a public method foo , Sub makes this method private. Now, the following code will compile fine, because the declared type bar is Parent:

 Parent bar = new Sub(); bar.foo(); 

However, it is not clear how this should behave. One possibility is to allow it to cause a runtime error. Another would be to simply allow it, which would allow you to call the private method from the outside, just by clicking on the parent class. None of these alternatives is acceptable, so it is not allowed.

+18
Oct 21 '09 at 13:04
source share

Because subtypes should be used as instances of their supertype.

+1
Oct 21 '09 at 13:01
source share



All Articles