有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

没有带受保护访问修饰符的访问修饰符的java重写方法

重写方法时,不允许降低继承方法的可见性。根据下表,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()(请参见子类)时,我得到了错误:

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

MyInterface中的方法没有访问修饰符,子类中的方法受到保护,因此更容易访问。我错过了什么

public interface MyInterface {
  void f();
}

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

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

共 (5) 个答案

  1. # 1 楼答案

    在java接口中, 所有的方法都是公开的。 所有变量都是公共静态最终变量。(常数)

  2. # 2 楼答案

    接口方法与生俱来的public

    给予

    protected void f(); 
    

    或者

    private void f();
    

    在MyInterface中,查看您得到了什么

  3. # 3 楼答案

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

  4. # 4 楼答案

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

  5. # 5 楼答案

    来自Javadoc

    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。因此,不能使用public以外的任何修饰符重写/隐藏此方法