为什么要将已实现的接口方法声明为 "public"?

Why should I declare implemented interface methods as "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()

Camel

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

在接口中,您将方法 getGait() 声明为 public。即使您没有在接口中将方法声明为 public,它也是 public.

但是在您的 class 中,您已将此方法声明为 package private。这是不允许的,因为它会降低 implemented 方法的可见性。

为了避免这个问题。在您的 class 中将此方法声明为 public,或者删除您的 class 实现具有此方法签名的接口的声明 (implements Rideable)。

根据面向对象的基础知识,接口仅包含 public 方法。所以当你实现接口时,你应该将它声明为 public ,否则它会给你编译时错误。

谢谢。

在接口中,字段是隐式的 public static final,接口中的方法默认是 public

请阅读继承规则:

http://www.codejava.net/java-core/the-java-language/12-rules-of-overriding-in-java-you-should-know

其中一个说,"The overriding method must not have more restrictive access modifier"。因此,您正在验证 Camel class 中的 getGait()。如果您没有在 class 的方法中提供访问修饰符,那么默认情况下它是 default。这意味着您将访问修饰符从 public 限制为 default。因此打破了 ovveriding 的规则,这就是它抱怨的原因。

接口的基本用法之一可以是检查 conformance.For 示例 class 实现 Comparable 接口必须提供 compareTo 方法,从而提供一种机制来比较class 的对象。 这些方法 public 有意义的原因是任何使用此一致性的 class 必须能够在没有 Arrays [=22] 的任何 restriction.For 示例排序方法的情况下使用这些方法=] 仅当它实现 Comparable 并公开 compareTo 方法时才足以对 class 的对象进行排序(如果那是你想为 sorting.Of 课程提供的机制Comparator 也在那里)。所以简而言之,只有在接口的情况下可读或可用的契约才足够好(因此使方法 public 势在必行)。