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

Viewed 8518

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.

4 Answers

Assume parent class and child class with overriding method with public access modifier.

class Parent{

public void m(){
// method implementation
}

}
class Child extends Parent{
@Override
public void m(){
//child implementation
}
}

assume there are some classes which are utilising this functionality like this

Parent p = new Child();
p.m(); // this access is fine, because JVM calls Overriding method at run time

Now if we change the access of overriding method to anything less than public

class Child extends Parent{
@Override
void m(){
//Child implementation
}
}

Now some of the classes which were able to use the functionality of method m() may not be able access the function.This is not a desired behaviour.

Hence the rule is Overriding method should not decrease the scope of overridden method.

Related