Card 07/ 08
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.
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
| 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 |
String cachedName = null; | Yes | Another 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.
← → move through sections and cards