java - 使用 protected 访问修饰符覆盖没有访问修饰符的方法

标签 java overriding access-modifiers

当您覆盖方法时,您不能降低继承方法的可见性。根据下表,protectedno 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() { }
}

最佳答案

接口(interface)中的方法 implicitly具有 public 的访问修饰符。因此,当您使用 protected 实现它时,它是一个较弱的访问修饰符。

关于java - 使用 protected 访问修饰符覆盖没有访问修饰符的方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32345165/

相关文章:

css - 覆盖某些行的引导表悬停

java - 为什么 protected 修饰符在 Java 子类中的行为不同?

java - 如何在一些子类之间共享代码?

oop - 在 MATLAB 中覆盖父类(super class)方法和访问修饰符

java - Apache Wicket 6.12 扩展库

java - Mongotemplate聚合-获取结果数

Java LDAP - 确定用户是否在给定组中?

java - 基类构造函数被调用但不应该被调用

java - 何时以及由谁执行方法调用?

javascript - html文件正文中的外部CSS