[wp_ad_camp_1]
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
.
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 | package com.turreta.interface1; public class DefaultMethodsDemo1 { public static void main(String[] args) { // Using anonymous class ChildInterface ci = new ChildInterface() { }; System.out.println(ci.getId()); } } interface ParentInterface { default String getId() { return "Parent interface"; } } interface ChildInterface extends ParentInterface { default String getId() { return "Child interface"; } } |
Output
[wp_ad_camp_2]
1 | Child interface |
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.
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 | public class DefaultMethodsDemo2 { public static void main(String[] args) { ChildInterface ci = new ChildInterface() { @Override public String getId() { return "Programmer's own implementation"; } }; System.out.println(ci.getId()); } } interface ParentInterface { default String getId() { return "Parent interface"; } } interface ChildInterface extends ParentInterface { String getId(); } |
[wp_ad_camp_3]
Output
1 | Programmer's own implementation |