This question already has answers here:
Java getting an error for implementing interface method with weaker access
                                
                                    (5个答案)
                                
                        
                                3年前关闭。
            
                    
SubclassOne扩展了ClassOne并实现了InterfaceOne,两者均具有void doSomething(){}方法。但是,编译器显示错误消息,


  ClassOne中的doSomething()无法在
  试图分配较弱的访问权限的InterfaceOne已公开


有人可以告诉我为什么编译器显示此特定消息吗?背后的原因是什么?

public class ClassOne {
    void doSomething(){
        System.out.println("do something from InterfaceMethod class");
    }
}


public interface InterfaceOne {
    default void doSomething(){
        System.out.println("do something from InterfaceOne");
    }
}


public class SubclassOne extends ClassOne implements InterfaceOne{
    public static void main(String[] args) {

    }
}

最佳答案

接口中的方法为public。没有访问修饰符package-private的方法,即访问权限较弱。将public修饰符添加到doSomething中的ClassOne

public class ClassOne {
    public void doSomething(){
        System.out.println("do something from InterfaceMethod class");
    }
}


您可以在documentation上查看访问修饰符表

09-12 22:46