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.
Invest now in Acorns!!! 🚀
Join Acorns and get your $5 bonus!
Acorns is a micro-investing app that automatically invests your "spare change" from daily purchases into diversified, expert-built portfolios of ETFs. It is designed for beginners, allowing you to start investing with as little as $5. The service automates saving and investing. Disclosure: I may receive a referral bonus.
Invest now!!! Get Free equity stock (US, UK only)!
Use Robinhood app to invest in stocks. It is safe and secure. Use the Referral link to claim your free stock when you sign up!.
The Robinhood app makes it easy to trade stocks, crypto and more.
Webull! Receive free stock by signing up using the link: Webull signup.
More Related questions...
