7
votes

I understand that all fields in an Inteface is implicitly static and final. And this made sense before Java 8.

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

But when I tried declaring a field normally, it became static and final by default.

Is there a way to declare a non-static and non-final field in Interface in Java 8.

Or am I totally misunderstanding something here???

4
No. Nonstatic fields are the primary remaining difference between interfaces and abstract classes.Louis Wasserman

4 Answers

12
votes

All fields in interfaces in Java are public static final.

Even after addition of default methods, it still does not make any sense to introduce mutable fields into the interfaces.

Default methods were added because of interface evolution reasons. You can add a new default method 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;
        }
    }
}
3
votes

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

Having state (fields) in an interface would raise issues, in particular with relation to the diamond problem.

See also this entry that clarifies the difference between behaviour and state inheritance.

0
votes

I strongly do not recommend to do that. Use abstract classes instead. But if you really need it you can do some workaround trick with some wrapper class. Here is an example:

public interface TestInterface {

    StringBuilder best = new StringBuilder();

    default void test() {
        best.append("ok");
        System.out.print(best.toString());
    }
}
-2
votes

No - In java 8 you can't have not public static final fields in interfaces, unfortunately.

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

Scala allows interface with not static fields, and this opens up so many more possibilities for code reuse and composition than available in Java 8