Java 8 - Default Methods in Interfaces
Default Methods in Interfaces:
In Java 7,
* All methods inside interface are public & abstract if you declare or not.
* Every variable inside the interface, public static final if you declare or not.
In java 8,
* Concrete methods are allowed in the form of default method.
Eg.
interface Interf{
default void m1(){
System.out.println("default method");
}
}
Using Default Method:
Class Test implements Interf{
public static void main(String args[]){
Test t = new Test();
t.m1();
}
}
output: default method
Override default method:
Class Test implements Interf{
public void m1(){
System.out.println("override default method");
}
public static void main(String args[]){
Test t = new Test();
t.m1();
}
}
output: override default method
If we are using default method in the interface, when we implements two interfaces with same method name, there might be an issue
For example,
interface Left{
default void m1(){
System.out.println("first interface");
}
}
interface Right{
default void m1(){
System.out.println("second interface");
}
}
So while implementing both the interface in the same class, compiler might get confused which one need to implement, because both having same method. To avoid this we have some idea,
1. We have to give our own implementation in the class
2. We have to mention which interface need to refer
Class Test implements Left, Right{
public void m1(){
//1st solution
System.out.println("My own implementation");
//2nd solution
Left.super.m1();
}
}
In Java 7,
* All methods inside interface are public & abstract if you declare or not.
* Every variable inside the interface, public static final if you declare or not.
In java 8,
* Concrete methods are allowed in the form of default method.
Eg.
interface Interf{
default void m1(){
System.out.println("default method");
}
}
Using Default Method:
Class Test implements Interf{
public static void main(String args[]){
Test t = new Test();
t.m1();
}
}
output: default method
Override default method:
Class Test implements Interf{
public void m1(){
System.out.println("override default method");
}
public static void main(String args[]){
Test t = new Test();
t.m1();
}
}
output: override default method
If we are using default method in the interface, when we implements two interfaces with same method name, there might be an issue
For example,
interface Left{
default void m1(){
System.out.println("first interface");
}
}
interface Right{
default void m1(){
System.out.println("second interface");
}
}
So while implementing both the interface in the same class, compiler might get confused which one need to implement, because both having same method. To avoid this we have some idea,
1. We have to give our own implementation in the class
2. We have to mention which interface need to refer
Class Test implements Left, Right{
public void m1(){
//1st solution
System.out.println("My own implementation");
//2nd solution
Left.super.m1();
}
}
Comments
Post a Comment