问题
When I compile this code:
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";
}
}
I get the following error:
Camel.java:13: error: getGait() in Camel cannot implement getGait() in Rideable
String getGait() {
^
attempting to assign weaker access privileges; was public
1 error
How is the getGait method declared in the interface considered public?
回答1:
Methods declared inside interface are implicitly public. And all variables declared in the interface are implicitly public static final (constants).
public String getGait() {
return " mph, lope";
}
回答2:
All methods in an interface are implicitly public, regardless if you declare it explicitly or not. See more information in the Java Tutorials Interfaces section.
回答3:
All methods in interface are implicitly public. But inside a class if public is not mentioned explicitly, it has only package visibility. Through overriding, you can only increase visibility. You cannot decrease visibility. So modify the implementation of getGait() in the class camel as
public String getGait() {
return " mph, lope";
}
回答4:
Interface fields are public, static and final by default, and the methods are public and abstract
So when you are implementing interface the function call should be public Function should be
public String getGait() {
return " mph, lope";
}
回答5:
Make getGait() in Camel class (implemented class of Rideable) as public.
public String getGait() {
return " mph, lope";
}
来源:https://stackoverflow.com/questions/13160672/java-getting-an-error-for-implementing-interface-method-with-weaker-access