为什么我应该将已实现的接口方法声明为“ public”? [英] Why should I declare implemented interface methods as "public"?

查看:172
本文介绍了为什么我应该将已实现的接口方法声明为“ public”?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

编译上面的代码后,我得到了一个编译错误,与 getGait()方法的访问修饰符有关。请解释一下,为什么要用 public 访问修饰符声明 getGait()

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?

推荐答案

getGait()的骆驼 实现一个方法 Rideable 接口。默认情况下,所有接口方法都是 public (即使您没有在接口定义中明确指定),所以所有实现方法也必须是公共的,因为您不能降低接口方法的可见性。

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.

这篇关于为什么我应该将已实现的接口方法声明为“ public”?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆