Java在实现具有较弱访问权限的接口方法时出错

A K*_*A K 16 java interface

当我编译这段代码时:

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";
    }
}
Run Code Online (Sandbox Code Playgroud)

我收到以下错误:

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

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

Per*_*ror 35

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

public String getGait() {
  return " mph, lope";
}
Run Code Online (Sandbox Code Playgroud)


Kep*_*pil 8

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


小智 6

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

public String getGait() {
    return " mph, lope";
}
Run Code Online (Sandbox Code Playgroud)