Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When overriding a method, why can I increase access but not decrease it?

Why does Java specify that the access specifier for an overriding method can allow more, but not less, access than the overridden method? For example, a protected instance method in the superclass can be made public, but not private, in the subclass.

like image 220
yesilupper Avatar asked Jul 27 '11 21:07

yesilupper


People also ask

Can I decrease the access modifier visibility in overriding?

Yes, an overridden method can have a different access modifier but it cannot lower the access scope.

What are the restrictions when overriding a method?

Overridden methods must have the same name, argument list, and return type. The overriding method may not limit the access of the method it overrides. The overriding method may not throw any exceptions that may not be thrown by the overridden method.

What happens when you 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.

Why overridden 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.


1 Answers

It's a fundamental principle in OOP: the child class is a fully-fledged instance of the parent class, and must therefore present at least the same interface as the parent class. Making protected/public things less visible would violate this idea; you could make child classes unusable as instances of the parent class.

like image 99
Patrick87 Avatar answered Oct 20 '22 11:10

Patrick87