Java 教程说我可以有一个包私有接口,但我不能 [英] Java tutorial says I can have a package-private interface, but I can't
问题描述
在Java教程定义接口"中,它说
如果您没有指定接口是public
,您的接口将只能被定义在与接口相同的包中的类访问.
If you do not specify that the interface is
public
, your interface will be accessible only to classes defined in the same package as the interface.
然而,这个
interface PPInterface {
void foo();
void bar();
}
class NewClass implements PPInterface {
void foo() {}
void bar() {}
}
在 NewClass
中产生编译器错误,因为我试图分配较弱的访问权限;是公开的'.所以文档是错误的,或者我做错了什么,或者我误解了文档?
generates compiler errors in NewClass
because I am 'attempting to assign weaker access privileges; was public'. So the documentation is wrong, or I did something wrong, or I misinterpreted the documentation?
我想我不必使用界面——我喜欢它,因为它使事情井井有条.
I suppose I don't have to use an interface-- I like it because it keeps things nicely organized.
推荐答案
可以包私有的是接口本身,而不是其中的方法.您可以定义一个只能在定义它的包中使用的接口(按名称),但它的方法与所有接口方法一样是 public
.如果一个类实现了那个接口,它定义的方法必须是public
.这里的关键是接口类型在包外不可见,而不是方法.文档没有错误,因为使用接口中定义的方法与使用接口本身不同.
It's the interface itself that can be package-private, not the methods in it. You can define an interface that can only be used (by name) within the package it's defined in, but its methods are public
like all interface methods. If a class implements that interface, the methods it defines must be public
. The key thing here is that it's the interface type that isn't visible outside the package, not the methods. The docs are not incorrect, because using the methods defined in the interface is not the same as using the interface itself.
还要注意,在定义接口时,不要在方法定义之前添加 public
不会改变任何东西,因为方法都是隐式的 public
.
Also be aware that when defining an interface, not adding public
before a method definition doesn't change anything since the methods are all implicitly public
.
如果实现接口的类本身是包私有的,则接口方法的public
性显然不是问题.当然,如果单继承问题不妨碍您,您也可以使用抽象类而不是接口:
If the class(es) that you have implementing the interface are themselves package-private, the public
ness of the interface methods is obviously not an issue. You could also, of course, use an abstract class instead of an interface if the single-inheritance issue doesn't get in your way:
abstract class Whatever {
abstract void foo();
abstract void bar();
}
这篇关于Java 教程说我可以有一个包私有接口,但我不能的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!