Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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

like image 401
ria Avatar asked Oct 21 '09 12:10

ria


People also ask

Can we reduce the visibility of the overridden method in Java?

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.

Why subclass overriding method should not be more restrictive?

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.

Why a subclass would override a method?

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.

Which methods are not allowed to override in subclass?

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.


2 Answers

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.

like image 124
Joachim Sauer Avatar answered Sep 21 '22 03:09

Joachim Sauer


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.

like image 37
sepp2k Avatar answered Sep 21 '22 03:09

sepp2k