In the below code when I am having a class implementing two interfaces with same default method signature it ask me to override it. but in the overriden method why I have to use super keyWord to call the default method.
package practice;
interface interA{
public default void AImp(){
System.out.println("Calling Aimp from interA");
}
}
interface interB{
public default void AImp(){
System.out.println("Calling Aimp from interB");
}
}
public class Practice implements interA,interB {
public static void main(String[] args) {
Practice inter = new Practice();
inter.AImp();
}
@Override
public void AImp() {
interA.super.AImp();
}
}
I can do the same b using below code:
@Override
public void AImp() {
interA inter = new Practice();
inter.AImp();
}
解决方案
Practice class implements 2 interfaces.
Namely InterA and InterB.
The idiom used specifies which one of the 2 default methods you wish to call.
This is because the 2 methods have the same signature.
However when you override the signature on the Practice class like that:
package practice;
interface InterA {
public default void AImp() {
System.out.println("Calling Aimp from interA");
}
}
interface InterB {
public default void AImp() {
System.out.println("Calling Aimp from interB");
}
}
public class Practice implements InterA, InterB {
public static void main(String[] args) {
Practice inter = new Practice();
inter.AImp();
}
// @Override
// public void AImp() {
//
// interA.super.AImp();
// }
@Override
public void AImp() {
InterA inter = new Practice();
inter.AImp();
}
}
You do not get the same result.
You get:
Exception in thread "main" java.lang.StackOverflowError
at practice.Practice.AImp(Practice.java:35)
at practice.Practice.AImp(Practice.java:35)
at practice.Practice.AImp(Practice.java:35)
at practice.Practice.AImp(Practice.java:35)
at practice.Practice.AImp(Practice.java:35)
at practice.Practice.AImp(Practice.java:35)
at practice.Practice.AImp(Practice.java:35)
You reference an instance of Practice through the InterA interface, that forces the use of the implemented interface,which will instantiate again Practice and call AImp . This will recursively be repeated until a java.lang.StackOverflowError is thrown.