Which feature introduced in Java 8 allows interfaces to have methods with implementations?

Java MCQ: Which feature introduced in Java 8 allows interfaces to have methods with implementations?

a) Abstract methods
b) Default methods
c) Static methods
d) Anonymous methods

Answer:

b) Default methods

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

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top