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???
Interface variables are static because Java interfaces cannot be instantiated on their own; the value of the variable must be assigned in a static context in which no instance exists. The final modifier ensures the value assigned to the interface variable is a true constant that cannot be re-assigned by program code.
Default methods enable you to add new functionality to the interfaces of your libraries and ensure binary compatibility with code written for older versions of those interfaces. A static method is a method that is associated with the class in which it is defined rather than with any object.
Interface in Java is similar to class but, it contains only abstract methods and fields which are final and static. Since all the methods are abstract you cannot instantiate it. To use it, you need to implement this interface using a class and provide body to all the abstract methods int it.
because if you make a method final then you can not override it and the sole purpose of Interface is to have methods that will be overridden by all those class that implements that Interface.
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;
}
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With