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

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s