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
While over ridding or implementing the access level, we should go for same access level or wider to that access level.
private < (default) < protected < public
Public is wider most level.
In Interface all members are default public. So, While implementing or over ridding we have to go for only public.
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.
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.
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.