问题描述
当我实现接口
方法时,我被迫将其设为 public
方法。
When I implement an interface
method, I am forced to make it a public
method.
我们可能会遇到需要使用默认
的情况(如果在同一个包内访问)或保护
。
We may have cases where we want to use either the default
(like in case of access within the same package) or protected
.
任何人都可以解释这个限制背后的原因吗?
Can anyone please explain the reason behind this limitation?
推荐答案
接口用于定义类型的 public API - 仅限于此而不是实现。因此,您在接口中定义的任何方法(或静态成员)都是按照定义 public
。
Interfaces are meant to define the public API of a type - and only that, not its implementation. So any method (or static member) you define in an interface is by definition public
.
由于接口可以不包含任何具体的实现,没有办法从内部调用任何成员方法。并且声明这样的方法但是将它们调用到子类或完全不相关的客户端将意味着您的类型定义不完整且易碎。这就是为什么如果你需要定义受保护的或包访问成员,你可以在抽象类(也可能包含实现)中这样做。
Since an interface can't contain any concrete implementation, there is no way to call any member methods from within. And declaring such methods but leaving the calls to them to subclasses or totally unrelated clients would mean your type definition is incomplete and brittle. That is why if you need to define protected or package access members, you can do so in an abstract class (which may also contain implementation).
这篇关于我们为什么要将接口方法声明为public?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!