Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Overriding method that has no access modifier with protected access modifier

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() { }
}
like image 985
Stanko Avatar asked Sep 02 '15 05:09

Stanko


People also ask

Can we override method with different access modifier overridden?

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.

What are the possible access modifiers a protected method can have if it is overridden in sub class?

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.

What are the possible access modifiers a protected method?

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.

Which modifier Cannot override?

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.


2 Answers

Methods in interfaces implicitly have the access modifier of public. So when you implement it with protected, it is a weaker access modifier.

like image 70
Amila Avatar answered Sep 21 '22 23:09

Amila


Methods in interfaces are implicitly marked public and not default

like image 43
Juned Ahsan Avatar answered Sep 23 '22 23:09

Juned Ahsan