Java因实现访问较弱的接口方法而出错

当我编译这段代码时:

interface Rideable { String getGait(); } public class Camel implements Rideable { int x = 2; public static void main(String[] args) { new Camel().go(8); } void go(int speed) { System.out.println((++speed * x++) + this.getGait()); } String getGait() { return " mph, lope"; } } 

我收到以下错误:

 Camel.java:13: error: getGait() in Camel cannot implement getGait() in Rideable String getGait() { ^ attempting to assign weaker access privileges; was public 1 error 

如何在接口中声明的getGait方法被公开?

在接口内声明的方法是隐式public 。 并且在接口中声明的所有变量都是隐式public static final (常量)。

 public String getGait() { return " mph, lope"; } 

无论您是否明确声明, interface中的所有方法都是隐式public 。 请参阅Java Tutorials Interfaces部分中的更多信息。

interface中的所有方法都是隐式public 。 但是如果没有明确提及public,则在类中,它只有包可见性。 通过覆盖,您只能提高可见性。 你无法降低能见度。 所以在类camel中修改getGait()的实现为

 public String getGait() { return " mph, lope"; } 

接口字段默认为public,static和final,方法是public和abstract

所以当你实现接口时,函数调用应该是public函数应该是

 public String getGait() { return " mph, lope"; }