Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java getting an error for implementing interface method with weaker access

Tags:

java

interface

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?

like image 796
A K Avatar asked Oct 31 '12 14:10

A K


People also ask

How can we avoid implementing all methods interface in Java?

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.

Can a class implementing an interface have more methods?

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.

Is it mandatory to implement all the methods of an interface?

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.

Can Java interfaces have implementations?

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.


1 Answers

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";
}
like image 160
PermGenError Avatar answered Sep 23 '22 18:09

PermGenError