【问题标题】:Java - the inherited method com.example.project.ConcreteA cannot hide the abstract method in com.example.project.MyInterfaceJava - 继承的方法 com.example.project.ConcreteA 无法隐藏 com.example.project.MyInterface 中的抽象方法
【发布时间】:2015-04-29 13:20:38
【问题描述】:

由于某种原因,我不能将接口中的方法声明为仅包;它自动声明为公共。这是简化的代码:

package com.example.project;

public interface MyInterface {

    void foo();
    Thing bar(); // The class Thing is in the com.example.project package, but what it does isn't important.

}



package com.example.project;

public abstract class SimpleConcrete implements MyInterface { // Initializes all methods as hooks
    
    protected Thing bar = new Thing();
    
    void foo() {}
    Thing bar() { return bar }
    
}
    


package com.example.project;

public class ConcreteA extends SimpleConcrete {
    
    void bar() {
        // code here...
    }
    
}



package com.example.project;

public class ConcreteB extends SimpleConcrete {
    
    void bar() {
        // more code here...
    }
    
}

当我尝试编译这个时,这些错误来了,所有连接:

文件: C:\ProjectFolder\com\example\project\SimpleConcrete.java [行:7]

错误:无法降低从 me.mathmaniac.everworlds.Block 继承的方法的可见性

文件: C:\ProjectFolder\com\example\project\ConcreteA.java [行:3]

错误:继承的方法com.example.project.SimpleConcrete.foo()无法隐藏com.example.project.MyInterface中的公共抽象方法

文件: C:\ProjectFolder\com\example\project\ConcreteB.java [行:3]

错误:继承的方法com.example.project.SimpleConcrete.foo()无法隐藏com.example.project.MyInterface中的公共抽象方法

有人知道如何解决这个问题,还是我必须让我的接口对整个 Java 代码公开,而不仅仅是对包开放? 出于安全原因,我想保持方法只对包开放,但需要,我会尝试找到另一种解决问题的方法。

【问题讨论】:

    标签: java inheritance interface access-modifiers


    【解决方案1】:

    Java 接口中的所有方法都是隐式公共的。更多信息请看这里:http://docs.oracle.com/javase/tutorial/java/IandI/interfaceDef.html

    你可以这样声明接口包级别:

    interface MyInterface {
    
        void foo();
        Thing bar();
    }
    

    这至少会将其封装在该包中。

    【讨论】:

    • @MathManiac 不确定我是否理解正确。你说你想让这些方法只能被包访问。我建议的解决方案实现了这一点。
    【解决方案2】:

    接口中声明的所有方法都是implicitly public

    接口中的所有抽象、默认和静态方法都隐含为public,因此您可以省略public 修饰符。

    要对方法有任何其他访问修饰符,您必须将接口转换为abstract 类,并将方法转换为abstract 方法。

    【讨论】:

    • 谢谢!太糟糕了,它不能是一个接口,OOP 等等。
    猜你喜欢
    • 2015-12-26
    • 1970-01-01
    • 1970-01-01
    • 2012-04-25
    • 1970-01-01
    • 2010-09-29
    • 1970-01-01
    • 2014-07-09
    • 2012-11-17
    相关资源
    最近更新 更多