java私有数据的对外接口,Java教程说我可以有一个包 - 私有接口,但我不能

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.

However, this

interface PPInterface {

void foo();

void bar();

}

class NewClass implements PPInterface {

void foo() {}

void bar() {}

}

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.

解决方案

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.

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.

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();

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值