使用受保护的访问修饰符覆盖没有访问修饰符的方法

Overriding method that has no access modifier with protected access modifier

重写方法时,不允许降低继承方法的可见性。根据以下 table,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

但是当我尝试覆盖 f()(参见 SubClass)时,我得到了错误:

无法降低从 MyInterface 继承的方法的可见性。

MyInterface 中的方法没有访问修饰符,SubClass 中的方法是受保护的,因此更易于访问。我在这里错过了什么?

public interface MyInterface {
  void f();
}

public abstract class MyClass {
  protected abstract void f();
}

public class SubClass extends MyClass implements MyInterface{
   protected void f() { }
}

接口 implicitly 中的方法具有 public 的访问修饰符。所以当你用protected实现它时,它是一个较弱的访问修饰符。

接口中的方法隐式标记为 public 而不是 default

在 java 的学习者范围内,这是一个很好的问题。但是你必须记住,有默认和隐式访问修饰符,比如接口在这种情况下是隐式的 public 默认 .

public interface MyInterface {
  void f();
}

public interface MyInterface {
  public void f();
} 

两者隐式相同。接口的设计方式使其行为公开。

在java界面中, 所有的方法都是public。 所有变量都是 public static final.(constants)

接口方法天生带有public

给予

protected void f(); 

private void f();

在 MyInterface 中看看你得到了什么。

来自 Java doc:

The access modifier (§6.6) of an overriding or hiding method must provide at least as much access as the overridden or hidden method, as follows:

  1. If the overridden or hidden method is public, then the overriding or hiding method must be public; otherwise, a compile-time error occurs.
  2. If the overridden or hidden method is protected, then the overriding or hiding method must be protected or public; otherwise, a compile-time error occurs.
  3. If the overridden or hidden method has default (package) access, then the overriding or hiding method must not be private; otherwise, a compile-time error occurs.

接口中的方法默认为public。所以你不能 override/hide 这个方法使用除 public.

以外的任何修饰符