Java getting an error for implementing interface method with weaker access

北慕城南 提交于 2019-12-17 05:04:26

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!