Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why `private static` field is not allowed in Java 8 interface?

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?

like image 704
Kamil Jarosz Avatar asked Jul 16 '15 10:07

Kamil Jarosz


People also ask

Why static method is not allowed in interface?

This is because it's not allowed in java, since Object is the base class for all the classes and we can't have one class level static method and another instance method with same signature.

Can a static field be private in Java?

Just like an instance variables can be private or public, static variables can also be private or public.

Does Java 8 allow static methods in interfaces?

Since Java8 you can have static methods in an interface (with body). You need to call them using the name of the interface, just like static methods of a class.

CAN interfaces have private static methods?

2. Defining Private Methods in Interfaces. Private methods can be implemented static or non-static. This means that in an interface we are able to create private methods to encapsulate code from both default and static public method signatures.


1 Answers

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.

like image 87
Brian Goetz Avatar answered Sep 22 '22 07:09

Brian Goetz