我是Java的新手,正在尝试学习继承的概念。当我尝试使用
从主类的identifyMyself方法()中调用EggLayer的identifyMyself()方法时System.out.println(EggLayer.super.identifyMyself());
它按预期工作。但是,当我尝试使用相同的语句从主类的main方法()调用EggLayer的identifyMyself()方法时,编译器会生成一个错误:"而不是封闭类: EggLayer&#34 ;.
有人可以向我解释为什么会这样吗?
interface Animal {
default public String identifyMyself() {
return "I am an animal.";
}
}
interface EggLayer extends Animal {
default public String identifyMyself() {
return "I am able to lay eggs.";
}
}
interface FireBreather extends Animal {
@Override
default public String identifyMyself(){
return "I'm a firebreathing animal";
}
}
public class Dragon implements EggLayer, FireBreather {
public static void main (String... args) {
Dragon myApp = new Dragon();
System.out.println(myApp.identifyMyself());
/**
*Not allowed, compiler says "not a enclosing class: EggLayer"
*System.out.println(EggLayer.super.identifyMyself());
*/
}
public String identifyMyself(){
//Call to EggLayer.super.identifyMyself() allowed
System.out.println(EggLayer.super.identifyMyself());
return "im a dragon egglayer firebreather";
}
}
答案 0 :(得分:1)
你的代码中的问题是你的龙类实现了两个接口:
default public String identifyMyself()
方法都返回不同的东西。 eggLayer也不是一个类,它是一个接口