by BehindJava

Java interview question on interfaces implemented by class with same default method in two interfaces

Home » java » Java interview question on interfaces implemented by class with same default method in two interfaces

Java interview question on interfaces implemented by class with same default method in two interfaces

Lets say we have two interfaces i.e. MyInterface and MyInterface2 implemented by by a class Example and those two interfaces contains same method i.e. newMethod() with body.

Since java 8 we can have static and default methods in interfaces with method body.

Now instance of Example class is created and newMethod is called with object reference When we do so, We get this error.

Duplicate default methods named newMethod with the parameters () and () are inherited from the types MyInterface2 and MyInterface

Sample Code Snippet:

public interface MyInterface {	
	default void newMethod(){  
        System.out.println("Newly added default method");  
    }  
    void existingMethod(String str);  

}public interface MyInterface2 {
	
	default void newMethod(){  
        System.out.println("Newly added default method1");  
    }  
    void disp(String str);  
}

public class Example implements MyInterface, MyInterface2{ 
    public void existingMethod(String str){           
        System.out.println("String is: "+str);  
    }  
    public void disp(String str){
    	System.out.println("String is: "+str); 
    }
    
    public static void main(String[] args) {  
    	Example obj = new Example();
    	
        obj.newMethod();     
    }  
}

We can overcome this by using super keyword in Java it is a reference variable which is used to refer immediate parent class object.

Code Snippet:

public class Example implements MyInterface, MyInterface2{ 
    public void existingMethod(String str){           
        System.out.println("String is: "+str);  
    }  
    public void disp(String str){
    	System.out.println("String is: "+str); 
    }
	 @Override 
	 public void newMethod() 
	 { 
	 MyInterface.super.newMethod(); 	 }
	public static void main(String[] args) {  
    	Example obj = new Example();
        obj.newMethod();     
    }  
}

Output:

Newly added default method