Interface fields in Java

In Java, all interface fields are compiled into public static final no matter their initial declaration:

public interface Interface {

	String LITTERAL= "hi, there";
	String NEW_STRING_OBJ = new String("new string object");
}

which after compiled and desassembled:

javap Interface

yields:

public interface Interface{
    public static final java.lang.String LITTERAL;
    public static final java.lang.String NEW_STRING_OBJ;
    static {};
}

An interesting thing to note about the above example is that final fields that are constants, like primitives and string litterals, are replaced or inlined during compile time, therefore if changed, all source codes that are referencing them need to be recompiled to pick-up the change. In the above example the LITTERAL constant is such a case whereas the NEW_STRING_OBJ field reference holds a runtime construct, that of a new String object, thus not adhering to the above recompilation rule.

Advertisements