Card 07/ 08

ExerciseDifficulty: Advanced1 min

Six Members: Which May an Interface Hold

Six declarations, one per line, all inside an interface. Decide for each whether it compiles, and if it does, what it implicitly becomes. Write all six 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 six 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

The seventh line is the trap. String cachedName = null; compiles, and it is not the instance field it looks like — it is another public static final constant, shared by everything, permanently null.

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