SHARE

As we know Java 8 is one of the major version with multiple major changes. One of these changes is Concept of default method. Using this concept we can define an Interface with method body. Afterwards we can put the implementation of methods in interface.

Need of Such Interface:

When we need to add a method in an older interface then problem arises. Problem is that all classes implementing that interface need to be changed. It is of course not feasible. So from Java 8 we can define method in the interface which need not to be implemented in classes.

How:

We can define method body in interface using keyword default. If we implement method in interface and do not use default keyword then compile time error will generate. So default methods in an interface are not mandatory to implement in the class.

We need not to use default keyword to define static methods. As all other methods in interface, default and static methods are also public but not abstract.

Example:

Lets take a look at following code.

TestInterface.java

TestClass.java

WithMain.java

After running this code we will get output like this;

Output

Problems:

Problem may arise when

  • A class implements two interface
  • Both of these interface contain default method with same signature

In this case we need to implement the same method in base class implementing these interfaces¬† otherwise error will be generated. Error may like “Duplicate default methods named aaa with the parameter (p..) and (p..) are inherited from the types Interface1 and Interface2”.

Interfaces with method body

Lets assume another Interface in above example:

NextInterface.java

Now Edit above Test Class like this

TestClass.java

and WithMain.java

Here Output will seem like

I hope this post will be helpful. Drop questions in comment box regarding this.

 

Facebook Comments

comments