Why `private static` field is not allowed in Java

2019-02-21 14:45发布

问题:

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?

回答1:

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.



回答2:

Interfaces are not classes. They have no private state. Even a public logger in the interface is a design smell and an abuse of interfaces.

The use case for static fields in interfaces is mainly for compile-time constants, not for stateful objects.



回答3:

The goal of interface is to define something implemented by other classes. A private field does not define anything as it is not visible outside the interface. Hence it does not make any sense in this construct. It may be some hacks how to use it (maybe from interface inner classes) but would not look like a good design anyway.

If you actually implement part of the functionality, use abstract class instead.



回答4:

Interface is like a blueprint of any class, where you declare your members. Any class that implement that interface is responsible for its definition. Private members can only be accessed by same class member, which does not make sense in terms of interface. Protected members can be accessed by same class member and inherited class members, but in case of interface we never extend an interface, we implement it. So any interface can only contain public methods generally,