【问题标题】:doSomething() in ClassOne can't implement doSomething() in InterfaceOne, attempt to assign weaker access privilege, was public [duplicate]ClassOne 中的 doSomething() 无法在 InterfaceOne 中实现 doSomething(),尝试分配较弱的访问权限,已公开 [重复]
【发布时间】:2016-04-10 08:42:05
【问题描述】:

SubclassOne扩展ClassOne并实现InterfaceOne,两者都有void doSomething(){}方法。但是,编译器显示错误信息,

ClassOne 中的 doSomething() 无法实现 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
  • 我认为问题是关于 classone 没有实现 interfaceone,但仍然出现错误。它不是那个的副本
  • @TamasHegedus 错误不在ClassOne 中。该消息仅引用ClassOne,因为SubclassOne 试图覆盖它。错误出现在SubclassOne 中,用于将doSomething 继承为私有包并尝试将其实现为public 以实现InterfaceOne。这是一个完全相同的副本。
  • @Pillar 所以发生这种情况是因为接口中存在默认实现。有趣的。我认为应该在答案中指出这一点
  • @TamasHegedus 不,这与default 无关。如果只是一个没有default的标准方法声明,也会出现同样的错误。

标签: java interface subclass superclass


【解决方案1】:

在这种情况下,您的SubclassOne 将提供一个满足超类和接口的实现。因此,由于两种方法的访问修饰符存在冲突,您会收到这样的错误消息。

(您的ClassOne 的访问修饰符不是public。它是包可见的。)

【讨论】:

    【解决方案2】:

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

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

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

    【讨论】:

    • @Pillar 我不认为它是重复的。至少不是您标记为重复的内容。
    • 为什么不呢?他们在问同样的事情。大多数upvoted answer 和你说的完全一样。
    • @Pillar 在另一篇文章中,OP 没有收到接口和父类之间冲突的错误。
    • 效果是一样的。当接口要求它是public 时,您有一个类在私有包中实现方法(无论是通过继承还是直接)。我们不需要另一个问题。
    • @Pillar 我想我们只会同意不同意。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2022-07-22
    • 1970-01-01
    • 2012-07-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-01-12
    相关资源
    最近更新 更多