In Java, you can extend from another interface using the extends keyword. But Java 8 has default methods. What happens if we extend another interface that has the same default methods as our interface?
It gets re-declared in the "child" interface.
Re-declare with different Implementation
Consider these codes. We have two (2) interfaces and one of them extends the other. The ParentInterface has a default method that returns the String"Parent interface". The other interface, ChildInterface, extends from the ParentInterface.
Java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
packagecom.turreta.interface1;
publicclassDefaultMethodsDemo1{
publicstaticvoidmain(String[]args){
// Using anonymous class
ChildInterface ci=newChildInterface(){
};
System.out.println(ci.getId());
}
}
interfaceParentInterface{
defaultStringgetId(){
return"Parent interface";
}
}
interfaceChildInterfaceextendsParentInterface{
defaultStringgetId(){
return"Child interface";
}
}
Output
[wp_ad_camp_2]
1
Childinterface
Re-declare as an abstract method
If we do not wish to use any default implementation, we can re-declare the default method as an abstract method. It is now up to the users of the interface to provide their own implementations of the abstract method.
Java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
publicclassDefaultMethodsDemo2{
publicstaticvoidmain(String[]args){
ChildInterface ci=newChildInterface(){
@Override
publicStringgetId(){
return"Programmer's own implementation";
}
};
System.out.println(ci.getId());
}
}
interfaceParentInterface{
defaultStringgetId(){
return"Parent interface";
}
}
interfaceChildInterfaceextendsParentInterface{
StringgetId();
}
[wp_ad_camp_3]
Output
1
Programmer'sown implementation
528 total views
, 1 views today
Got comments or suggestions?
We disabled the comments on this site to fight off spammers,
but you can still contact us via our Facebook page!.