问题
interface Rideable {
String getGait();
}
public class Camel implements Rideable {
int weight = 2;
String getGait() {
return " mph, lope";
}
void go(int speed) {++speed;
weight++;
int walkrate = speed * weight;
System.out.print(walkrate + getGait());
}
public static void main(String[] args) {
new Camel().go(8);
}
}
Upon compiling the above code I've got a compilation error, related to access modifier of getGait()
method. Please explain, why should I declare getGait()
with public
access modifier?
回答1:
getGait()
of Camel
implements a method of the Rideable
interface. All interface methods are public
by default (even if you don't specify it explicitly in the interface definition), so all implementing methods must be public too, since you can't reduce the visibility of the interface method.
回答2:
In the interface you have method getGait()
declared as public
. Even you do not state a method as a public in interface it is public.
But in your class, you have declared this method as package private. It is not allowed, because it reduces the visibility of the implemented method.
To avoid this problem. either declare this method as public in your class, or remove declaration (implements Rideable
) that your class implements the interface with this method signature.
回答3:
According object oriented fundamentals, interface contains only public methods. so when you implements interface, you should declare it as a public , otherwise it give you compile time error.
Thanks.
回答4:
One of the basic usage of interfaces can be to check conformance.For example a class implementing Comparable
interface must provide compareTo
method and hence providing a mechanism to compare objects of the class.
The reason these methods being public makes sense is that any class which utilizes this conformance must be able to use these methods without any restriction.For example sort method of Arrays
class will be good enough to sort objects of a class only if it implements Comparable
and exposes the compareTo
method(If thats the mechanism you want to provide for sorting.Of course Comparator
is also there). So in a nutshell, a contract is only good enough if its readable or usable in case of interfaces(thus making methods public
imperative).
回答5:
In Interface, the fields are implicitly public static final
and the methods in an interface are by default public
.
Please read the rules of Inheritance:
http://www.codejava.net/java-core/the-java-language/12-rules-of-overriding-in-java-you-should-know
One of which says, "The overriding method must not have more restrictive access modifier". So you are ovveriding the getGait()
in Camel
class. If you do not provide the access modifier in methods of class then by defaults its default
. Which mean you are restricting the access modifier from public
to default
. Hence breaking the rule of ovveriding which is why its complaining.
来源:https://stackoverflow.com/questions/43465021/why-should-i-declare-implemented-interface-methods-as-public