Site icon

Impact of interface’s default method on multiple inheritance (Java 8 /example)

Example – multiple inheritance in java

Let us take example to understand the multiple inheritanc

  1. Suppose we have Mother and Father interfaces
    • Mother interface has
      • cook method
      • height method
    • Father interface
      • runner method
      • height method
    • Mother & Father interface has common method i.e. height
  2. Son class implements Mother and Father interfaces.
    • What all methods it needs to implement ? [Refer Fig 1]
    • cook method
    • runner method
    • height method
Fig 1: Multiple inheritance prior to java 8

What is impact of interface’s default method on multiple inheritance?

Fig 2: Default method and multiple inheritance

Program – Impact of interface’s default method on multiple inheritance (Java8)

package org.learn;

interface Mother {
	default void height() {
		System.out.println("I am short");
	}

	default void cook() {
		System.out.println("Cooking expert");
	}
}

interface Father {
	default void runner() {
		System.out.println("Marathon champion");
	}

	default void height() {
		System.out.println("I am tall");
	}
}

class Son implements Mother, Father {
	@Override
	public void height() {
		Father.super.height();
	}
}

public class MultipleInheritence {

	public static void main(String[] args) {
		Son son = new Son();
		son.cook();
		son.runner();
		son.height();
	}
}

Output – Impact of interface’s default method on multiple inheritance (java8)

Cooking expert
Marathon champion
I am tall
Exit mobile version