【问题标题】:Java getting an error for implementing interface method with weaker accessJava在实现访问较弱的接口方法时出错
【发布时间】:2012-10-31 14:50:44
【问题描述】:

当我编译这段代码时:

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";
    }
}

我收到以下错误:

Camel.java:13: error: getGait() in Camel cannot implement getGait() in Rideable
String getGait() {
       ^
  attempting to assign weaker access privileges; was public
1 error

接口中声明的getGait方法如何被认为是公共的?

【问题讨论】:

  • 在接口中声明的方法隐式为public。这就是语言的工作方式。对于实现该接口的类,必须明确说明该方法的访问修饰符。在您的情况下,String getGait()protected,因此是错误消息。
  • 这个错误是不言自明的,您需要在 Camel 类中公开 getGait()。
  • @mre ... getGait 方法实际上具有默认可见性... package-private... 不受保护。

标签: java interface


【解决方案1】:

在接口内声明的方法隐式为public。并且接口中声明的所有变量都是隐式的public static final(常量)。

public String getGait() {
  return " mph, lope";
}

【讨论】:

    【解决方案2】:

    interface 中的所有方法都隐含为public,无论您是否显式声明它。在Java Tutorials Interfaces section 中查看更多信息。

    【讨论】:

      【解决方案3】:

      interface 中的所有方法都隐含为public。但是在一个类中,如果没有明确提到 public,它只有包可见性。通过覆盖,您只能增加可见性。你不能降低能见度。所以修改骆驼类中getGait()的实现为

      public String getGait() {
          return " mph, lope";
      }
      

      【讨论】:

        【解决方案4】:

        接口字段默认是public、static和final,方法是public和abstract

        所以当你实现接口时,函数调用应该是public 函数应该是

        public String getGait() {
          return " mph, lope";
        }
        

        【讨论】:

          【解决方案5】:

          将 Camel 类(Rideable 的实现类)中的 getGait() 设为公开。

          public String getGait() {
                  return " mph, lope";
              }
          

          【讨论】:

            猜你喜欢
            • 2017-02-03
            • 1970-01-01
            • 2014-12-03
            • 1970-01-01
            • 1970-01-01
            • 2023-03-04
            • 1970-01-01
            • 1970-01-01
            • 2012-07-23
            相关资源
            最近更新 更多