Thursday 3 July 2014

Default Method and Multiple Inheritance Ambiguity Problems

Since Java8 support default implementations in interfaces, there is an ambiguity problem exist.

For Example
lets take Interface1, Interface2 both have default implementation for print method, lets say 'MyClass' implements both the interfaces, then there is an ambiguity related to print method usage.
public interface Interface1 {
    default void print(){
        System.out.println("I am in Interface1");
    }
}

public interface Interface2 {
     default void print(){
        System.out.println("I am in Interface2");
    }
}

public class MyClass implements Interface1, Interface2{

}

When you tries to compile the above program compiler throws below error.
MyClass.java:1: error: class MyClass inherits unrelated defaults for print() from types Interface1 and Interface2
public class MyClass implements Interface1, Interface2{
       ^
1 error

In order to solve this user has to provide implementation for the method print in the class.

public class MyClass implements Interface1, Interface2{
 public void print(){
  System.out.println("I am in MyClass");
 }
}

Inside the print method of class, you can call the default methods of the interaces like below.
public class MyClass implements Interface1, Interface2{
 public void print(){
  System.out.println("I am in MyClass");
  Interface1.super.print();
  Interface2.super.print();
 }
}








Prevoius                                                 Next                                                 Home

No comments:

Post a Comment