【发布时间】:2012-10-31 14:50:44
【问题描述】:
当我编译这段代码时:
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。这就是语言的工作方式。对于实现该接口的类,必须明确说明该方法的访问修饰符。在您的情况下,String getGait()是protected,因此是错误消息。 -
这个错误是不言自明的,您需要在 Camel 类中公开 getGait()。
-
@mre ... getGait 方法实际上具有默认可见性... package-private... 不受保护。