Which statement is true about private methods in interfaces introduced in Java 9?

Java MCQ: Which statement is true about private methods in interfaces introduced in Java 9?

a) They can be called from outside the interface
b) They can only be called within default or static methods of the same interface
c) They must be overridden by implementing classes
d) They are automatically public

Answer:

b) They can only be called within default or static methods of the same interface

Explanation:

Private methods in interfaces, introduced in Java 9, can only be called within default or static methods of the same interface. These private methods are not accessible from outside the interface, nor can they be called by implementing classes. They are designed to encapsulate common code that can be shared among multiple default or static methods within the interface, improving code reuse and maintainability.

Here’s an example of a private method in an interface:

interface MyInterface {
    default void method1() {
        commonMethod();
    }

    default void method2() {
        commonMethod();
    }

    private void commonMethod() {
        System.out.println("Common code");
    }
}

In this example, commonMethod() is a private method that can be called by method1() and method2(), which are default methods in the interface. Private methods in interfaces help avoid code duplication and make interfaces more powerful by allowing internal logic to be shared.

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