Which new feature in Java 9 allows interfaces to have private methods?

Java MCQ: Which new feature in Java 9 allows interfaces to have private methods?

a) Private constructors
b) Private methods in interfaces
c) Private fields
d) Private inner classes

Answer:

b) Private methods in interfaces

Explanation:

Java 9 introduced the ability to define private methods in interfaces. This feature allows interfaces to have methods that are accessible only within the interface itself and cannot be called from outside. Private methods in interfaces can be used to share common code between default methods or static methods in the interface.

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

interface MyInterface {
    default void method1() {
        System.out.println("Default method 1");
        commonMethod();
    }

    default void method2() {
        System.out.println("Default method 2");
        commonMethod();
    }

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

In this example, commonMethod() is a private method in the interface MyInterface. It is called by both method1() and method2(), which are default methods. The private method helps avoid code duplication within the interface.

Private methods in interfaces provide a way to structure and organize code within interfaces, making them more maintainable and reducing redundancy.

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