为什么Java 8接口中不允许使用`private static`字段? [英] Why `private static` field is not allowed in Java 8 interface?

查看:576
本文介绍了为什么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");
    }
}

我收到错误

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

当我删除 private 修饰符时,代码编译,但我不希望包中的其他类看到这个字段。

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

为什么Java实际上不允许我做这样的事情有意义吗?

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

推荐答案

在世界前Java-8视图中,接口纯粹用于接口契约和私有成员纯粹是为了实现而存在,所以这个限制是完全合理的。

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.

在后Java-8世界中,接口可以承载行为(但不是状态),它开始是否合理地询问是否应该将其他类的特性应用于接口。 (但是,仅仅因为某些东西可能是合理的并不意味着它必须得到支持;构建世界通常有不止一种合理的方式。)

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,将支持接口中的私有方法。

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

这篇关于为什么Java 8接口中不允许使用`private static`字段?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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