November 28, 2023
java

Java 8 Default Methods


Interfaces in Java always contained method declaration not their definitions (method body). There was no way of defining method body / definition in interfaces. This is because historically Java didn’t allow multiple inheritance of classes. It allowed multiple inheritance of interfaces as interface were nothing but method declaration. This solves the problem of ambiguity in multiple inheritance. Since Java 8 it is now possible to add method bodies in interfaces.

Java 8 has a new feature called Default Methods. It is now possible to add method bodies into interfaces!

public interface Math {

int add(int a, int b);

default int multiply(int a, int b) {
return a * b;
}
}
In above Math interface we added a method multiply with actual method body.

If you add a single method in an interface, it breaks everything. You need to add its implementation in every class that implements that interface. Imagine in real world how many custom classes would change.

Consider following example:

interface Person {
//adds a java 8 default method
default void sayHello() {
System.out.println(“Hello World!”);
}
}

class Sam implements Person {

}

public class Main {

public static void main(String [] args) {

Sam sam = new Sam();

//calling sayHello method calls the method
//defined in interface
sam.sayHello();
}
}
Output:

Hello World!        

What about Multiple Inheritance?
Adding method definitions in interfaces can add ambiguity in multiple inheritance. isn’t it? Well, it does. However Java 8 handle this issue at Compile type. Consider below example:

interface Person {
default void sayHello() {
System.out.println(“Hello”);
}
}

interface Male {
default void sayHello() {
System.out.println(“Hi”);
}
}

class Sam implements Person, Male {

}
In this example we have same method sayHello in both interfaces Person and Male. Class Sam implements these interfaces. So which version of sayHello will be inherited? We’ll if you try to compile this code in Java 8, it will give following error.

class Sam inherits unrelated defaults for sayHello() from types Person and Male class Sam implements Person, Male { ^ 1 error

So that solves multiple inheritance problem. You cannot implement multiple interfaces having same signature of Java 8 default methods (without overriding explicitly in child class).

We can solve the above problem by overriding sayHello method in class Sam.

class Sam implements Person, Male {
//override the sayHello to resolve ambiguity
void sayHello() {
System.out.println(“Hi”);
}
}

Leave a Reply

Your email address will not be published. Required fields are marked *