Java MCQ: Which feature introduced in Java 8 allows interfaces to have methods with implementations?
Answer:
Explanation:
Java 8 introduced default methods, which allow interfaces to have methods with implementations. This feature was added to enable the evolution of interfaces without breaking existing implementations.
A default method in an interface is defined using the default
keyword followed by the method implementation. For example:
interface MyInterface {
default void myDefaultMethod() {
System.out.println("This is a default method");
}
}
In this example, myDefaultMethod
is a default method in MyInterface
. Any class that implements MyInterface
can either use the default implementation or override the method.
Default methods are particularly useful in cases where new methods are added to existing interfaces. They allow the interface to evolve by adding new methods without requiring all implementing classes to provide an implementation, thus maintaining backward compatibility.
Reference links:
https://www.rameshfadatare.com/learn-java-programming/
https://www.javaguides.net/p/java-tutorial-learn-java-programming.html