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?
However, you can avoid this by following the below approach: Declare the missing methods abstract in your class. This forces you to declare your class abstract and, as a result, forces you to subclass the class (and implement the missing methods) before you can create any objects.
Your class can implement more than one interface, so the implements keyword is followed by a comma-separated list of the interfaces implemented by the class.
Yes, it is mandatory to implement all the methods in a class that implements an interface until and unless that class is declared as an abstract class.
All methods of an Interface do not contain implementation (method bodies) as of all versions below Java 8. Starting with Java 8, default and static methods may have implementation in the interface definition.
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";
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With