default methods in interface but only static final fields

Codebender picture Codebender · Jun 30, 2015 · Viewed 8.6k times · Source

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???

Answer

Crazyjavahacking picture Crazyjavahacking · Jun 30, 2015

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;
        }
    }
}