Java教程说我可以有一个包 - 私有接口,但我不能 [英] Java tutorial says I can have a package-private interface, but I can't

查看:1295
本文介绍了Java教程说我可以有一个包 - 私有接口,但我不能的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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 。这里的关键是它是在包外面看不到的接口 type ,而不是方法。文档不正确,因为使用界面中定义的方法与使用界面本身不同。

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 publicness 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屋!

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