43

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

Joachim Sauer
  • 302,674
  • 57
  • 556
  • 614
ria
  • 7,904
  • 11
  • 39
  • 46

3 Answers3

66

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.

Joey
  • 344,408
  • 85
  • 689
  • 683
Joachim Sauer
  • 302,674
  • 57
  • 556
  • 614
  • 3
    But why are we not allowed to override a protected method and change it to private? Since the public interface is still the same, it doesn't break LSP this way. – Pacerier Aug 23 '14 at 07:32
  • 1
    The public interface does not change, but the protected does. Code in the parent class cannot access the methods of its own flesh and blood :( – Elazar Sep 07 '15 at 22:08
19

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.

sepp2k
  • 363,768
  • 54
  • 674
  • 675
  • C++ solves this problem by controlling the visibility of the inheritance relation. Also strange in Java is that super class constructors can call (virtual) subclass methods, i.e. in a scope, where the subclass instance is in an undefined state. – Sam Ginrich Jan 29 '23 at 13:02
1

Because subtypes have to be usable as instances of their supertype.

z -
  • 7,130
  • 3
  • 40
  • 68