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

  • Java 8 has introduced default method for interfaces, which provides the default implementation of method.
  • Prior to java 8 interfaces does not have any default keyword
    • There were no conflicts if class inherits multiple interfaces having same method (Prior to Java8).

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?

  • Son class implementing Mother and Father interface, what all methods it will have
    1. Son class will have default implementation of cook method (if not implemented).
      • Its not mandatory to implement the cook method.
    2. Son class will have default runner method (if not implemented).
      • Its not mandatory to implement the runner method
    3. What about height, its there in both Father & Mother interface?

      • Its ambiguous, which default method it should inherits (Mother or Father)
      • Son class needs to specify which method it will inherit.
interface default method muliple 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
Scroll to Top