Which Java 8 feature allows interfaces to include methods with implementations?

Java MCQ: Which Java 8 feature allows interfaces to include methods with implementations?

a) Functional interfaces
b) Default methods
c) Lambda expressions
d) Stream API

Answer:

b) Default methods

Explanation:

Default methods in Java 8 allow interfaces to include methods with implementations. This feature was introduced to enable interface evolution without breaking existing implementations. A default method is defined with the default keyword in an interface and provides a concrete implementation that can be used by implementing classes.

For example:

interface MyInterface {
    default void myMethod() {
        System.out.println("This is a default method.");
    }
}

In this example, myMethod() is a default method in MyInterface. Any class that implements MyInterface can use this default implementation without providing its own.

Default methods are particularly useful for adding new functionality to interfaces without forcing all implementing classes to change. They help maintain backward compatibility while still allowing interfaces to evolve.

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