Interface Default Method in Java 8 or Above
Default Method in Interface
In Java earlier versions, before 1.8, it was not possible to create any method with a body in Interface, the only abstract method with public access modifier was supported, but now from version 1.8, it is possible to declare default method that has body also.
If the programmer wants to add new service or logic in the interface without doing modification on the implementation class of interface, then now from Java version 1.8 he/she can use default methods in the interface.
Let’s understand by example:
interface Message {
public abstract void msg ();
public default void msg2()
{
System.out.println(“Default method in Interface”);
}
}
public class Main implements Message {
public void msg ()
{
System.out.println(“This is Functional Interface Method”);
}
public static void main (String [] args)
{
Message m1 = new Main ();
m1.msg();
m1.msg2();
}
}
Points to be Remember of Default Members:
1. Any number of default method can be declared in the interface
2. A default method can be overload or override
3. We cannot override java.lang.Object method in the interface as default methods.