Default methods in the interface, but only static end fields

I understand that all fields in Inteface are implicitly static and trailing . And that made sense before Java 8.

But with the introduction of default methods , interfaces also have all the capabilities of an abstract class. And therefore, non-static and non-finite fields are needed.

But when I tried to declare the field normally, it became static and final by default.

Is there a way to declare non-static and non-final fields in an interface in Java 8 .

Or am I completely misunderstanding something here?

+5
source share
3 answers

All fields in interfaces in Java public static final .

Even after adding default methods, it still makes no sense to introduce mutable fields into interfaces.

Default methods have been added due to reasons for the evolution of the interface. You can add a new default interface to the interface, but it only makes sense if the implementation uses already defined methods in the interface:

 public interface DefaultMethods { public int getValue(); public default int getValueIncremented() { if (UtilityMethod.helper()) { // never executed, just to demonstrate possibilities "string".charAt(0); // does nothing, just to show you can call instance methods return 0; } return 1 + getValue(); } public static class UtilityMethod { public static boolean helper() { return false; } } } 
+7
source

No - in Java 8, all fields are static and final, as in previous versions of Java.

The presence of state (fields) in the interface will cause problems, in particular with respect to the diamond problem .

See also this entry for an explanation of the difference between behavior and state overlapping.

+2
source

Not. In java 8 you cannot have fields in interfaces, unfortunately.

But I hope that in the future this will be added to the language.

Scala allows you to interact with fields, and this opens up much more possibilities for reuse and compilation of code than is available in Java 8

0
source

All Articles