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
package pack001; public interface TestInterface { void add(); static void sub(){ System.out.println("Static method in the interface"); } default void show(){ System.out.println("show method in interface"); } }
TestClass.java
package pack001; public class TestClass implements TestInterface{ public void add(){ System.out.println("Add in overridden method"); } }
WithMain.java
package pack001; public class WithMain { public static void main(String args[]){ TestInterface ti=new TestClass();// or TestClass ti=new TestClass(); ti.show(); ti.add(); TestInterface.sub(); } }
After running this code we will get output like this;
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”.
Lets assume another Interface in above example:
NextInterface.java
package pack001; public interface NextInterface { default void show(){ System.out.println("show in nextInterface"); } }
Now Edit above Test Class like this
TestClass.java
package pack001; public class TestClass implements TestInterface,NextInterface{ public void show(){ System.out.println("show in the class"); } public void add(){ System.out.println("Add in overridden method"); } }
and WithMain.java
package pack001; public class WithMain { public static void main(String args[]){ TestClass ti=new TestClass(); ti.show(); ti.add(); TestInterface.sub(); } }
Here Output will seem like
show in the class Add in overridden method Static method in the interface
I hope this post will be helpful. Drop questions in comment box regarding this.