Java / Java 21 Interview Questions
What are default and static methods in Java interfaces?
Java 8 added default and static methods to interfaces, fundamentally changing the relationship between interfaces and abstract classes.
interface Validator {
// Abstract method — implementors must provide
boolean isValid(T value);
// Default method — provided implementation, can be overridden
default Validator and(Validator other) {
return value -> this.isValid(value) && other.isValid(value);
}
default Validator or(Validator other) {
return value -> this.isValid(value) || other.isValid(value);
}
default Validator negate() {
return value -> !this.isValid(value);
}
// Static factory method — belongs to the interface, not instances
static Validator of(Validator validator) {
return Objects.requireNonNull(validator);
}
}
// Usage
Validator notBlank = s -> !s.isBlank();
Validator notTooLong = s -> s.length() <= 100;
Validator combined = notBlank.and(notTooLong);
System.out.println(combined.isValid("hello")); // true
System.out.println(combined.isValid("")); // false
// Diamond problem resolution
interface A { default String hello() { return "A"; } }
interface B extends A { default String hello() { return "B"; } }
class C implements A, B {
// Must override — most-specific interface wins (B),
// but compiler forces explicit resolution
@Override public String hello() { return B.super.hello(); }
} Default methods enable interface evolution: adding a new method to an interface in a library no longer breaks all existing implementors, because the default provides backward compatibility. This is how Java 8 added methods like Collection.forEach(), List.sort(), and Map.getOrDefault() without breaking existing code.
More Related questions...