因为所有接口方法都是public,这是否意味着接口方法的所有实现也必须是public
since all interface method are public, does that mean all implementation of interface method must be public as well
既然所有的接口方法都是public,那是不是意味着接口方法的所有实现也必须是public?我读过子类只能分配
访问级别高于原始方法。我已经用一些代码试过了,它似乎是真的,但我只是想知道在哪里可以找到关于这个的文档?
Interface
被创建为 接口 以使用 class 实现它们的接口。
例如,我们实现了一个 Comparable
接口来信任 class 有 compareTo
方法,可以被其他 使用 classes.
所以这是不可能的,我认为这样做没有意义。
我没有找到与您的问题完全相关的文档部分,但可以从这部分理解:
If the overridden or hidden method is public, then the overriding or hiding method must be public; otherwise, a compile-time error occurs.
您可以在 Java Language Specification.
中找到该要求的官方文档
引用自8.4.8.3. Requirements in Overriding and Hiding:
The access modifier (§6.6) of an overriding or hiding method must provide at least as much access as the overridden or hidden method, as follows:
If the overridden or hidden method is public, then the overriding or hiding method must be public; otherwise, a compile-time error occurs.
If the overridden or hidden method is protected, then the overriding or hiding method must be protected or public; otherwise, a compile-time error occurs.
If the overridden or hidden method has package access, then the overriding or hiding method must not be private; otherwise, a compile-time error occurs.
如官方 Java Oracle 教程:
interfaces are a kind of contract all implementing classes have to stick to
这意味着,方法的签名、return 类型和访问修饰符不允许 更改。
https://docs.oracle.com/javase/tutorial/java/IandI/index.html
此外,如果您尝试使用 @Override
注释标记接口方法,编译器将抛出错误。
既然所有的接口方法都是public,那是不是意味着接口方法的所有实现也必须是public?我读过子类只能分配 访问级别高于原始方法。我已经用一些代码试过了,它似乎是真的,但我只是想知道在哪里可以找到关于这个的文档?
Interface
被创建为 接口 以使用 class 实现它们的接口。
例如,我们实现了一个 Comparable
接口来信任 class 有 compareTo
方法,可以被其他 使用 classes.
所以这是不可能的,我认为这样做没有意义。
我没有找到与您的问题完全相关的文档部分,但可以从这部分理解:
If the overridden or hidden method is public, then the overriding or hiding method must be public; otherwise, a compile-time error occurs.
您可以在 Java Language Specification.
中找到该要求的官方文档引用自8.4.8.3. Requirements in Overriding and Hiding:
The access modifier (§6.6) of an overriding or hiding method must provide at least as much access as the overridden or hidden method, as follows:
If the overridden or hidden method is public, then the overriding or hiding method must be public; otherwise, a compile-time error occurs.
If the overridden or hidden method is protected, then the overriding or hiding method must be protected or public; otherwise, a compile-time error occurs.
If the overridden or hidden method has package access, then the overriding or hiding method must not be private; otherwise, a compile-time error occurs.
如官方 Java Oracle 教程:
interfaces are a kind of contract all implementing classes have to stick to
这意味着,方法的签名、return 类型和访问修饰符不允许 更改。
https://docs.oracle.com/javase/tutorial/java/IandI/index.html
此外,如果您尝试使用 @Override
注释标记接口方法,编译器将抛出错误。