Understanding Java 8 Interface Default Methods and Their Compilation Constraints
This article explains Java 8 interface default methods, demonstrates why the provided code fails to compile due to accessing a non‑existent instance field, and clarifies how adding fields to an interface affects compilation, concluding that option A is the correct answer.
The following Java code defines an interface Nameable with default setName and getName methods that attempt to read and write a field name , a class Employee that implements the interface and declares a protected String name , and a class HR with a main method that creates an Employee , sets its name to "John Doe", and prints the result.
interface Nameable {
default void setName(String name) {
this.name = name;
}
default String getName() {
return this.name;
}
}
class Employee implements Nameable {
protected String name;
}
class HR {
public static void main(String[] args) {
Employee e = new Employee();
e.setName("John Doe");
System.out.println(e.getName());
}
}The multiple‑choice question asks which statement is true about the compilation result, offering four options: A) the interface Nameable cannot compile, B) class Employee cannot compile, C) class HR cannot compile, D) the program outputs "John Doe".
The article explains that default methods are instance methods defined in interfaces, but they cannot access instance fields because interfaces are not allowed to declare non‑static fields. Since Nameable does not contain a name field, the references to this.name inside the default methods refer to a non‑existent field, causing a compilation error. Consequently, option A is the correct answer.
If a field is added to the interface, it is implicitly public static final . Adding String name = "John Doe"; to Nameable would allow the getName default method to compile, but the setName default method would still fail because a final field cannot be reassigned. Therefore, even with the added field, the code as shown would not compile.
FunTester
10k followers, 1k articles | completely useless
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.