Default and Private Methods in Interfaces
In this class, We discuss Default and Private Methods in Interfaces.
The reader should have prior knowledge of interfaces in Java. Click Here.
First, we understand why default methods are allowed in interfaces.
Example:
interface A
{
void m1();
void m2();
}
Class B implements A
{
void m1()
{
}
void m2()
{
}
}
Class C implements A
{
void m1()
{
}
void m2()
{
}
}
In the above example, interface A is implemented in two classes.
After some time, suppose a new method is added to the interface A.
The two classes implementing interface A should be changed.
The new method is written default to avoid the changes in implemented classes.
The below example shows the syntax of the default method.
Example 1:
interface A
{
int p=20;
public static void staticmethod()
{
System.out.println(“static method”);
}
void m1();
public default void m5()
{
m6();
System.out.println(“this is default method”);
}
private void m6()
{
System.out.println(“This is private method”);
}
}
Class B implements A
{
public void m1()
{
System.out.println(“m1 method implemented in B”);
}
}
class test
{
public static void main(String args[])
{
B ob = new B();
ob.m1();
ob.m5();
}
}
We can use private methods from the Java 9 version.
The default methods can use private methods.