Consider the following case,
interface IFace1 {
default void printHello() {
System.out.println("IFace1");
}
}
interface IFace2 {
void printHello();
}
public class Test implements IFace1, IFace2 {
public static void main(String[] args) {
Test test = new Test();
test.printHello();
IFace1 iface1 = new Test();
iface1.printHello();
IFace2 iface2 = new Test();
iface2.printHello();
}
@Override
public void printHello() {
System.out.println("Test");
}
}
In above example I am getting following output which is quite expected.
Test
Test
Test
I have been reading about Java-8
default methods and specifically about Extending Interfaces That Contain Default Methods
2nd bullet : Redeclare the default method, which makes it abstract.
In above example where I have two interfaces which have default method with same name and when I implemented both I was only able to reach to the implementation of printHello
of Test
which refers to IFace2
.
I have few questions about this,
- How can I reach to the
printHello
method ofIFace1
and if I can't than why ? - Doesn't this behavior keep me away from the intended nature of
IFace1
which is may be now shadowed by other method ?
Quote says, you can make the default
method abstract
in it's child interface. For example,
interface IFace2 extends IFace1 {
void printHello();
}
Here when I implement IFace2
I won't be actually able to reach default
method of IFace1
that is exactly what is happening in my case.
new Test().printHello()
will always invoke the method declared inTest
, regardless of how you define the interfaces or whetherTest
implements them or not. – Didi