How to use a Default Methods in Java 8

There is a possibility that a class is implementing two interfaces with same default methods.
Let’s start with the simplest example possible:

package com.nourit.java8;

public class TestDefaultMethods {

  public static void main(String[] args) {
    System.out.println("------------- Cat -------------");
    Cat cat = new Animal();
    cat.print();
    System.out.println("-------------- Dog ------------");
    Dog dog = new Animal();
    dog.print();
    System.out.println("-------------The same Result -------------");
  }

}

interface Cat {
  default void print() {
    System.out.println("I am a Cat!");
  }

  static void sayMyaw() {
    System.out.println("Cat say Myaw!!");
  }
}

interface Dog {
  default void print() {
    System.out.println("I am a Dog!");
  }

  static void sayHaw() {
    System.out.println("Dog say Haw!!");
  }
}

class Animal implements Cat, Dog {
  public void print() {
    Cat.super.print();
    Cat.sayMyaw();
    Dog.super.print();
    Dog.sayHaw();
    System.out.println("we are animals!");
  }
}

Output:

------------- Cat -------------
I am a Cat!
Cat say Myaw!!
I am a Dog!
Dog say Haw!!
we are animals!
-------------- Dog ------------
I am a Cat!
Cat say Myaw!!
I am a Dog!
Dog say Haw!!
we are animals!
-------------The same Result -------------

 

NOUR-IT

IT Training Center for Java and Web technology. If you enjoy and like our tutorials and believe in our mission, Please Subscribe us on Youtube and follow us on Twitter, or befriend us on Facebook or Google Plus.

Schreibe einen Kommentar

Deine E-Mail-Adresse wird nicht veröffentlicht. Erforderliche Felder sind mit * markiert.

*