Card 07/ 08
All 8 cards
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.
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
| Declaration | Compiles? | What it is |
|---|---|---|
int MAX = 100; | Yes | Implicitly public static final — a constant, not a field |
String name(); | Yes | Implicitly public abstract — the method implementers must supply |
default String label() | Yes | A body every implementer inherits and may override |
static Thing of(String n) | Yes | Called as Thing.of(...), never through an instance |
Thing() { } | No | An interface has no constructor; there is nothing to construct |
private String pad(String s) | Yes, since Java 9 | A 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.