10.3 Java SE 8 Interface default and static Methods
Key Takeaways
A Java SE 8 interface default method must use the default keyword, provide a body, and is implicitly public (never static, final, abstract, private, or protected)
A subinterface may inherit a default, override it with a default, or redeclare the method as abstract.
A compatible public instance method inherited from a superclass can satisfy the interface method and takes precedence over an interface default. A superclass abstract method can keep the implementation obligation in place.
Conflicting inherited defaults require resolution. A class can provide a public override and, subject to direct-superinterface rules, call a selected default with
InterfaceName.super.method().Interface static methods are public and are not inherited. Outside the declaring interface, use its name or an applicable static import to call one.
Why Java SE 8 Added default and static Interface Methods
Java SE 8 added default methods with instance implementations and static methods owned by the interface. A default can let existing classes use a new interface method without adding an implementation. Inherited-name conflicts still need resolution. Examples in the Java SE 8 API include Collection.stream() and List.sort().
default Method Rules and Sub-Interface Choices
A default method is an instance method declared inside an interface using the default keyword and a { ... } method body. Like abstract interface methods, a default method is implicitly public.
Watch for these compiler traps on default methods:
- The
defaultkeyword is mandatory: Writing a non-staticinterface method with a body{ ... }withoutdefaultfails to compile (interface abstract methods cannot have body). - Body is mandatory: Writing
default void run();without{}fails to compile (missing method body, or declare abstract). - Forbidden modifiers: A
defaultmethod cannot beabstract,static,final,private, orprotected.
When a sub-interface extends an interface with a default method, it has three valid options:
- Inherit the
defaultmethod untouched. - Override it with a new
defaultmethod. - Redeclare it as
abstract(droppingdefaultand the body), which removes that inherited default and leaves concrete implementers needing a public implementation, whether declared or inherited from a class.
interface Notifier {
default String format(String msg) {
return "[INFO] " + msg;
}
}
interface UrgentNotifier extends Notifier {
// Option 3: redeclares format() as abstract (implicitly public abstract)
@Override
String format(String msg);
}
class EmailNotifier implements Notifier {
// Option 1: inherits Notifier's default format()
}
class SmsNotifier implements UrgentNotifier {
@Override
public String format(String msg) {
return "[URGENT] " + msg;
}
}
If SmsNotifier omitted format(String), compilation would fail because UrgentNotifier replaced the inherited default method with an abstract requirement.
Diamond Conflict Resolution Rules
When a class inherits methods with the same signature from multiple supertypes (a class and interfaces, or multiple interfaces), Java SE 8 resolves the diamond ambiguity using three deterministic rules:
- Class member first: A compatible public instance method inherited from a superclass or declared in the class satisfies the interface method. A weaker-access or incompatible declaration can cause a compile-time error. An inherited abstract superclass declaration can suppress the use of defaults, so a concrete implementation is still needed.
- Most-Specific Sub-Interface Wins: If
SubI extends BaseIand both define adefaultmethodm(), implementingSubI(or bothBaseI, SubI) usesSubI'sdefaultmethod without conflict. - Unrelated declarations: If a default and another override-equivalent method would both be inherited from unrelated interfaces, they conflict. A suitable class method resolves the conflict. The exception for a matching inherited abstract superclass declaration keeps the class’s abstract obligation instead of permitting an interface default to fill it.
Inside an instance method, InterfaceName.super.methodName(...) can select a default from a direct superinterface. The qualifier must not bypass a more specific declaration from another direct supertype.
interface Printer {
default String status() {
return "Printer Ready";
}
}
interface Scanner {
default String status() {
return "Scanner Ready";
}
}
// Rule 3: Must override status() to resolve conflict between Printer and Scanner
class AllInOne implements Printer, Scanner {
@Override
public String status() {
return Printer.super.status() + " + " + Scanner.super.status();
}
}
class LegacyDevice {
public String status() {
return "Legacy OK";
}
}
// Rule 1 (Class Wins): Compiles without overriding status()!
class ModernDevice extends LegacyDevice implements Printer, Scanner {
}
public class DiamondDemo {
public static void main(String[] args) {
System.out.println(new AllInOne().status());
System.out.println(new ModernDevice().status());
}
}
Output:
Printer Ready + Scanner Ready
Legacy OK
Tip
In AllInOne, Printer.super.status() explicitly selects Printer’s default. Plain super.status() starts with the class superclass, Object, which has no such method.
Decision Flow for default Method Conflicts
Interface static Methods (and Non-Inheritance)
An interface static method provides a utility helper bound to the interface type itself. Like default methods, an interface static method has a { ... } body and is implicitly public (and cannot be private, protected, default, or abstract in Java SE 8).
However, interface static methods follow a critical rule that differs sharply from class static methods:
- Class
staticmethods can be called through a subclass name or even an instance reference of that class. - Interface
staticmethods are NEVER inherited by implementing classes or sub-interfaces. Use the declaring interface name to qualify a call, or use an unqualified call when the method is in scope, such as inside the declaration or after a valid static import. An object expression is not a valid qualifier.
interface Validator {
static boolean isNonEmpty(String s) {
return s != null && !s.trim().isEmpty();
}
boolean validate(String input);
}
interface StrictValidator extends Validator {
}
public class NameValidator implements StrictValidator {
@Override
public boolean validate(String input) {
return Validator.isNonEmpty(input);
}
public static void main(String[] args) {
NameValidator nv = new NameValidator();
Validator v = nv;
System.out.println(Validator.isNonEmpty("Java")); // Compiles: true
// All three lines below FAIL compilation:
// StrictValidator.isNonEmpty("Java"); // Not inherited by sub-interface
// NameValidator.isNonEmpty("Java"); // Not inherited by implementing class
// v.isNonEmpty("Java"); // Illegal static interface method call
}
}
Because interface static methods are not inherited, two interfaces I1 and I2 can each declare static void helper() with no conflict in class C implements I1, I2, and C may define its own static void helper() or instance void helper() completely independently without hiding or overriding anything in I1 or I2.
Comparing Java SE 8 Interface Method Types
| Feature | Abstract Method | default Method | static Method |
|---|---|---|---|
| Keyword required | abstract optional | default required | static required |
Method body { ... } | Forbidden (ends in ;) | Required | Required |
| Implicit access in Java 8 | public | public | public |
| Inherited by implementing class | Contract inherited | Implementation inherited | Not inherited |
| Inherited by sub-interface | Contract inherited | Implementation inherited | Not inherited |
| Invocation | Instance call on an implementation | Instance call. A legal InterfaceName.super can choose a default explicitly. | Declaring interface qualifier or an unqualified name in scope |
What is the result of compiling and running the following code?
interface Walk {
default int getSpeed() { return 5; }
}
interface Run {
default int getSpeed() { return 10; }
}
public class Cat implements Walk, Run {
public int getSpeed() {
return Run.super.getSpeed();
}
public static void main(String[] args) {
System.out.println(new Cat().getSpeed());
}
}
Compilation fails because Cat inherits conflicting default methods from Walk and Run
Compiles and prints 10
Compilation fails on Run.super.getSpeed()
Compiles and prints 5
Given:
interface Base {
default String label() { return "Base"; }
}
interface Sub extends Base {
String label();
}
class Item implements Sub {
}
Which statement is true?
Item compiles cleanly and inherits "Base" from Base.label()
Sub fails to compile because it omits the default keyword on label()
Item fails to compile because Sub redeclared label() as abstract
Sub fails to compile because an interface cannot override a default method
Which call compiles in Java SE 8 given interface MathUtil { static int doubleIt(int n) { return n * 2; } } and class Calculator implements MathUtil { }?
MathUtil.doubleIt(4);
Calculator.doubleIt(4);
new Calculator().doubleIt(4);
MathUtil m = new Calculator(); m.doubleIt(4);
Sections you finish are checked off in the contents.