Java 8, default method

Before Java8 we have an only abstract method in the interface. But Java8 has removed this restriction and we can have methods with the body in the interface. An interface can have a default or static method. We will see what is the reason for adding default method.

Java8 has added lambda expression, this added many new methods in the already existing interface. Let us see this as an example. Here is the code for java.util.Iterator interface. This has 3 methods. There was a need to add lambda related method forEachRemaining in java8. Now assume a case where there is no default in the scene, then all the existing class which implements Iterator, needs to modify the implementation to add this new method. This needs to be done for JDK as well as application classes. This would have created problem and may have made all existing running application difficult to move to java8, i.e Java8 would not have been backward compatible.

The cleaver solution for this problem was to add a new default construct, which allows users to write method in the interface without the need to implement these in subclasses. Once we add default forEachRemaining method, it is automatically available for all the implementing class. This is fine. But what will happen when we implement two Interfaces and each of them has same default method.

The code will not compile. Here are 3 classes which have default method.

interface TestI1{
default void show(){
System.out.println("Default TestI1");
}
}
interface TestI2{
default void show() {
System.out.println("Default TestI2");
}
}
class Test implements TestI1, TestI2{
public static void main(String args[]) {
Test d = new Test();
d.show();
}
}

This will show following compilation error. Test.java:1: error: class Test inherits unrelated defaults for show() from types TestI1 and TestI2 class Test implements TestI1, TestI2

We need to provide own implementation of the show method in Test class.


class Test implements TestI1, TestI2{
public void show(){
System.out.println("Test show");
}
public static void main(String args[]) {
Test d = new Test();
d.show();
}
}

Now how can we call the TestI1 and Test2 default show method? We can use super keyword to call super interfaces default method as shown below.

class Test implements TestI1, TestI2{
public void show() {
TestI1.super.show();
TestI2.super.show();
}
public static void main(String args[]){
Test d = new Test();
d.show();
}
}
Is’nt it a clever solution than making the java8 backward incompatible? 🙂

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s