static private java,为什么Java 8接口中不允许使用`private static`字段?

When I'm trying to compile the following code

public interface SomeInterface{

private static Logger logger = Logger.getLogger();

public default void someMethod(){

logger.info("someMethod: default implementation");

}

}

I get an error

Illegal modifier for the interface field SomeInterface.logger; only public, static & final are permitted

When I delete private modifier, code compiles, but I don't want other classes from the package to see this field.

Why Java doesn't allow me to do such thing when it actually does make sense?

解决方案

In the pre-Java-8 view of the world, interfaces were purely for interface contracts, and private members exist purely for implementation, so this restriction was completely sensible.

In the post-Java-8 world, where interfaces can carry behavior (but not state), it starts to be reasonable to ask whether other features of classes should be applied to interfaces as well. (However, just because something might be "reasonable" doesn't mean it must be supported; there is often more than one reasonable way to construct the world.)

In Java 9, private methods in interfaces will be supported.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值