14 December 2015

Multiple Defaults =

With default functions in interfaces, there is a possibility that a class is implementing two interfaces with same default methods.

public interface EducationalBook {
   default void print(){
      System.out.println("I am reading an Educational Book!");
   }
}

public interface ComicBook {
   default void print(){
      System.out.println("I am reading a Comic Book!");
   }
}

There are two Solutions for that -

1. First solution is to create an own method that overrides the default implementation.

public class Book implements EducationalBook, ComicBook {
   void print(){			
      System.out.println("I read books like Educational books and Comic books!");
   }
}

2. Second solution is to call the default method of the specified interface using super.

public class Book implements EducationalBook, ComicBook {
   void print(){
      EducationalBook.super.print();
      ComicBook.super.print();
   }
}

Example -

In interface EducationalBook.java

public interface EducationalBook {
    default void read(){
        System.out.println("I am reading an Educational Book!");
    }
}

In interface ComicBook.java

public interface ComicBook {
    default void read(){
        System.out.println("I am reading a Comic Book!");
    }
}

In Class Book.java which implements multiple interfaces EducationalBook, ComicBook.

public class Book implements EducationalBook, ComicBook {

    @Override
    public void read() {
        System.out.println("I read books like Educational books and Comic books!");
        EducationalBook.super.read();
        ComicBook.super.read();
    }

    public static void main(String args[]){
        Book book = new Book();
        book.read();
    }
}

Output

I read books like Educational books and Comic books!
I am reading an Educational Book!
I am reading a Comic Book!


blog comments powered by Disqus