This is follow-up from the previous post where we talk about the changes in Interfaces in JDK 8 .
So now we know that Interfaces can also have default methods with the implementation .
Default Methods enable us to add new functionality to existing interfaces and ensure binary compatibility with code written for older versions of those interfaces . In particular , default methods allows us to add methods that accept lambda expressions as parameters to existing interfaces .
We specify the default methods with the "default" keyword at the beginning of the method signature . All the method declarations in an interface are implicitly "public" so we can omit the "public" modifier .
Suppose that we have an interface , MyInterface :
public interface MyInterface
{
void method1(int i);
void method2(String s);
void method3(double d){
System.out.println("d is "+d);
}
}
And we have a class, MyClass that implements this Interface :
public MyClass implements MyInterface
{
void method1(int i)
{
System.out.print("i is"+i);
}
void method2(String s)
{
System.out.print("s is"+s);
}
}
This will compile successfully and method3 will be already defined for MyClass .
We will look into different scenarios that are possible with this implementation . Like what will happen if we implement two interfaces and both of them have a default method with the same signature. Or what will happen if we implement the extended interface and both the parent & child interfaces have same default methods.
So now we know that Interfaces can also have default methods with the implementation .
Default Methods enable us to add new functionality to existing interfaces and ensure binary compatibility with code written for older versions of those interfaces . In particular , default methods allows us to add methods that accept lambda expressions as parameters to existing interfaces .
We specify the default methods with the "default" keyword at the beginning of the method signature . All the method declarations in an interface are implicitly "public" so we can omit the "public" modifier .
Suppose that we have an interface , MyInterface :
public interface MyInterface
{
void method1(int i);
void method2(String s);
void method3(double d){
System.out.println("d is "+d);
}
}
And we have a class, MyClass that implements this Interface :
public MyClass implements MyInterface
{
void method1(int i)
{
System.out.print("i is"+i);
}
void method2(String s)
{
System.out.print("s is"+s);
}
}
This will compile successfully and method3 will be already defined for MyClass .
We will look into different scenarios that are possible with this implementation . Like what will happen if we implement two interfaces and both of them have a default method with the same signature. Or what will happen if we implement the extended interface and both the parent & child interfaces have same default methods.