What are default methods in Java interfaces?
Answer
Default methods, introduced in Java 8, allow interfaces to provide concrete method implementations. Before Java 8, adding a new method to an interface would break all implementing classes. Default methods solve the backwards-compatibility problem — you can add new methods to interfaces without breaking existing implementations. Declare with the default keyword: default void log(String message) { System.out.println(message); }. Implementing classes can override default methods. If a class implements two interfaces with the same default method, the class must override it to resolve the ambiguity. Default methods enable evolution of interfaces over time — they are the reason Java could add stream-related methods to existing collection interfaces.
Previous
What is a method reference in Java?
Next
What is the difference between Comparable and Comparator?
More Java Questions
View all →- Intermediate What is the Java Collections Framework?
- Intermediate What is the difference between ArrayList and LinkedList?
- Intermediate What is HashMap in Java and how does it work internally?
- Intermediate What is the difference between HashMap and HashTable in Java?
- Intermediate What is the difference between HashMap and LinkedHashMap?