Card 07/ 08

ExerciseDifficulty: Advanced1 min

Practice: Which Members an Interface May Declare

Seven declarations inside an interface: which compile, and what each implicitly becomes.

An interface may hold behaviour and constants, and never per-object state. Using that rule, decide for each of the seven declarations below whether it compiles inside an interface, and if it does, what it implicitly becomes. Write all seven down first.

java
interface Thing {
    int MAX = 100;
    String name();
    default String label() { return "thing: " + name(); }
    static Thing of(String n) { return () -> n; }
    Thing() { }
    private String pad(String s) { return " " + s; }
    String cachedName = null;
}
Which of the seven compile, and what each one really is
Each declaration, whether it compiles, and what it becomes
DeclarationCompiles?What it is
int MAX = 100;YesImplicitly public static final: a constant, not a field
String name();YesImplicitly public abstract: the method implementers must supply
default String label()YesA body every implementer inherits and may override
static Thing of(String n)YesCalled as Thing.of(...), never through an instance
Thing() { }NoAn interface has no constructor; there is nothing to construct
private String pad(String s)Yes, since Java 9A helper the default and static methods may call
String cachedName = null;YesAnother public static final constant, not a field

The last line is the trap. String cachedName = null; compiles, and it is not the instance field it looks like: it is a constant, shared by everything, permanently null.

The rule underneath all seven: an interface may hold behaviour and constants, and never per-object state. That single line is what makes implementing several of them safe.