Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is it not allowed to narrow down scope of a method while overriding

In Java, when I override a method the compiler flags off any attempt to narrow down the visibility as an error. For ex: I can't override a public method as protected, while I can override a protected method as public.

I am interested in knowing the design decision/thinking behind this rule.

like image 621
user1464472 Avatar asked Jul 14 '12 14:07

user1464472


People also ask

Does overriding method decrease the scope of overridden method?

Hence the rule is Overriding method should not decrease the scope of overridden method. Thanks for contributing an answer to Stack Overflow! Please be sure to answer the question.

How do you prevent a method from being overridden?

Method 1: Using a static method This is the first way of preventing method overriding in the child class. If you make any method static then it becomes a class method and not an object method and hence it is not allowed to be overridden as they are resolved at compilation time and overridden methods are resolved at runtime.

What are the rules for overriding a method in a class?

The rules are there so you don't lose the original throws declaration by widening the specificity, as the polymorphism means you can invoke the overriden method on the superclass. The overriding method must NOT throw checked exceptions that are new or broader than those declared by the overridden method.

What is overriding a method in Java?

Overriding means redefining a behaviour (method) again in the child class which was already defined by its parent class but to do so overriding method in the child class must follow certain rules and guidelines. With respect to the method it overrides, the overriding method must follow following rules.


2 Answers

A subclass should always satisfy the contract of the superclass. See Liskov Substitution principle.

The visibility of methods is part of this contract. So anything publicly visible in the superclass should be public in the subclass as well.

like image 83
Don Roby Avatar answered Oct 15 '22 15:10

Don Roby


Consider a class B which inherits from A. A.m() is public. Now consider this code:

A obj = new B();
obj.m();

Should this call be allowed? Yes, it should, because obj is an object of type A! It is also an object of type B, but that is not necessarily known to the one using the object.

Every object of type A must adhere to the contract (interface) for A. B extends A and must therefore also adhere to that contract.

like image 32
Emil Vikström Avatar answered Oct 15 '22 15:10

Emil Vikström