Java 8 changes in interface

Kode Shaft
Algo Shaft
Published in
2 min readAug 4, 2019

In this post we are gonna discuss about the changes in Java 8 interface

Before java 8 all the methods in the interface were abstract and we were not allowed to have any method definition. But java 8 has completely changed the scenario by introducing two methods as described below:

  1. Default Method:

To create a default method in java interface, we have to use “default” keyword like shown below

public interface MyInterface{

void method1();

default void method2(){

System.out.println(“Testing”);

}

}

The interesting thing here is that you can define the default method in the interface, so that the classes extending it doesn’t have to implement.

Now the question is what is the need for default method ?? and why suddenly in Java 8 the change came ??

Java 8 has added functional programming feature in it and for that it has to define some extra methods in already existing interfaces.But now they can’t add simply extra abstract method in all those interfaces as then all the implementer has to change their code which is not acceptable. To overcome this problem they made all the new methods as default in respective interfaces and provided implementation in the interface itself.

But wait….

We have one problem of multiple inheritance due to this feature. What if two interface A and B has same default method and class C implements A and B ????

in that case we have to provide the implementation of the default method in C class else it will give compile time error.

So as a summary we can say if default method with same signature is coming to a class from more than one parent interface, the class has to provide the implementation of default method in it.

One thing to be noted that whatever method Object class has(e.g. equals())you can’t use the same signature in the interface by appending default to it, that’s not allowed.

2. Static Method:

In java 8 we can define a static method and it doesn’t need to be declared as default.

public interface MyInterface{

static void method1(){

System.out.println(“Testing Static Method”);

}

}

method1 can be called directly by MyInterface.method1() without anyone implementing the interface.

Happy Learning 😎

--

--

Kode Shaft
Algo Shaft

Blog made by two tech enthusiasts Dipesh and Gagandeep living in India. Here you can find informations about things happening around technology industry.