Default Method
We create default methods inside the interface.
Default methods are also called Defender methods.
The default methods are non-abstract methods.
The functional interface contains a default and an abstract method.
Default methods enable you to add new functionality to the interfaces.
We can override default method, If you do not override them, they are the methods which will be invoked by caller classes.
The default methods allow us to add new methods to an interface that are automatically available in the implementations.
If each added method in an interface is defined with implementation, then no implementing class is affected.
An implementing class can override the default implementation provided by the interface.
We added the new methods(default method) in the existing interfaces in such a way so that they are backward compatible.
We must need to implements the default method in the implementation classes.
To call a default method you need to use the object of the implementing class.
We can inherit the default method.
Default method can be redeclare by making it abstract.
Syntax
public interface Test
{
void normalMethod();//normal interface methods
default void defaultMethod()
{
// default method implementation
}
}
Program:-
interface Test
{
default void m1()
{
System.out.println("Default Method...");
}
void normalMethod(String str); //abstract method
}
public class child implements Test
{
public void normalMethod(String str) // implementing abstract method
{
System.out.println(str);
}
public static void main(String[] args)
{
child obj = new child();
obj.m1(); //calling the default method of interface
obj.normalMethod("Program of defaultMethod"); //calling the abstract method of interface
}
}
OutPut:-
Default Method...
Program of defaultMethod