【问题标题】:Error generated when tried to call superclass method from the main method of the program尝试从程序的主方法调用超类方法时产生错误
【发布时间】:2015-12-31 07:52:04
【问题描述】:

我是 Java 新手,正在尝试学习继承的概念。当我尝试使用

从主类的 identifyMyself 方法()中调用 EggLayer 的 identifyMyself()方法时
System.out.println(EggLayer.super.identifyMyself());

它按预期工作。但是,当我尝试使用相同的语句从主类的 main method() 调用 EggLayer 的 identifyMyself() 方法时,编译器会生成错误消息:“不是封闭类:EggLayer”。

有人可以向我解释为什么会这样吗?

  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";

    }
}

【问题讨论】:

    标签: java subclass superclass default-method


    【解决方案1】:

    您的代码中的问题是您的 dragon 类实现了两个接口: default public String identifyMyself() 方法都返回不同的东西。另外 eggLayer 不是一个类它是一个接口

    【讨论】:

      猜你喜欢
      • 2018-08-21
      • 2015-05-17
      • 1970-01-01
      • 1970-01-01
      • 2012-05-09
      • 2011-10-24
      • 2010-11-21
      • 1970-01-01
      相关资源
      最近更新 更多