हाँ, आप Java 9 से इंटरफेस में प्राइवेट मेथड्स का उपयोग कर सकते हैं।
उदाहरण
interface MyInterface {
public abstract void demo();
public default void defaultMethod() {
privateMethod();
staticPrivateMethod();
System.out.println("This is a default method of the interface");
}
public static void staticMethod() {
staticPrivateMethod();
System.out.println("This is a static method of the interface");
}
private void privateMethod(){
System.out.println("This is a private method of the interface");
}
private static void staticPrivateMethod(){
System.out.println("This is a static private method of the interface");
}
}
public class InterfaceMethodsExample implements MyInterface {
public void demo() {
System.out.println("Implementation of the demo method");
}
public static void main(String[] args){
InterfaceMethodsExample obj = new InterfaceMethodsExample();
obj.defaultMethod();
obj.demo();
MyInterface.staticMethod();
}
}
आउटपुट
This is a private method of the interface This is a static private method of the interface This is a default method of the interface Implementation of the demo method This is a static private method of the interface This is a static method of the interface
Java 9 से पहले, इंटरफेस में केवल पब्लिक एब्स्ट्रैक्ट मेथड्स हो सकते थे। Java 8 में डिफ़ॉल्ट और स्टेटिक मेथड्स जोड़े गए, और Java 9 में प्राइवेट मेथड्स (इंस्टेंस और स्टेटिक दोनों) की अनुमति दी गई ताकि डिफ़ॉल्ट/स्टेटिक मेथड्स के बीच कोड शेयर किया जा सके।