当我编译这段代码时:
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)
小智 6
所有方法interface都是隐含的public.但如果没有明确提及public,则在类中,它只有包可见性.通过覆盖,您只能提高可见性.你无法降低能见度.所以修改getGait()类camel中的实现为
public String getGait() {
return " mph, lope";
}
Run Code Online (Sandbox Code Playgroud)