Middle
Can a private method be declared in an interface?
sobes.tech AI
Answer from AI
Starting from Java 9, private methods can be declared in interfaces. This helps to avoid code duplication between default methods (default) and static methods within the interface.
Private methods in interfaces are not visible outside the interface and are used to organize internal logic.
Example:
public interface MyInterface {
default void defaultMethod() {
commonLogic();
System.out.println("Default method");
}
static void staticMethod() {
commonLogic();
System.out.println("Static method");
}
private static void commonLogic() {
System.out.println("Common logic");
}
}
Thus, private methods help improve the structure and readability of interface code, avoiding repetition.