When you override methods you are not allowed to reduce the visibility of the inherited method. According to the following table, protected
is more accessible than no modifier
:
| Class | Package | Subclass | World ————————————+———————+—————————+——————————+——————— public | y | y | y | y ————————————+———————+—————————+——————————+——————— protected | y | y | y | n ————————————+———————+—————————+——————————+——————— no modifier | y | y | n | n ————————————+———————+—————————+——————————+——————— private | y | n | n | n y: accessible n: not accessible
But when I try to override f()
(see SubClass) then I get the error:
Cannot reduce the visibility of the inherited method from MyInterface.
The method in MyInterface has no access modifier and the one in SubClass is protected, so more accessible. What am I missing here?
public interface MyInterface {
void f();
}
public abstract class MyClass {
protected abstract void f();
}
public class SubClass extends MyClass implements MyInterface{
protected void f() { }
}
Yes, an overridden method can have a different access modifier but it cannot lower the access scope. Methods declared public in a superclass also must be public in all subclasses. Methods declared protected in a superclass must either be protected or public in subclasses; they cannot be private.
Yes, the protected method of a superclass can be overridden by a subclass. If the superclass method is protected, the subclass overridden method can have protected or public (but not default or private) which means the subclass overridden method can not have a weaker access specifier.
The protected access modifier is accessible within package and outside the package but through inheritance only. The protected access modifier can be applied on the data member, method and constructor. It can't be applied on the class.
Explanation: To disallow a method from being overridden, specify final as a modifier at the start of its declaration. Methods declared as final cannot be overridden.
Methods in interfaces implicitly have the access modifier of public
. So when you implement it with protected
, it is a weaker access modifier.
Methods in interfaces are implicitly marked public
and not default
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With