【问题标题】:Inheritance Errors in Java [duplicate]Java中的继承错误[重复]
【发布时间】:2014-09-15 06:50:23
【问题描述】:

我正在尝试java中的extends关键字,像这样:

帐户类别:

public class Account {
     public Account(...) {
         //Code...
     }
}

GameAccount 类:

public class GameAccount extends Account {
     public GameAccount(...) {
         //Code...
     }
}

但在 Eclipse 上,我收到一个看起来很讨厌的错误:

隐式超级构造函数 Account() 未定义。必须显式调用另一个构造函数。

我该如何解决这个问题?

【问题讨论】:

  • 它只是不知道应该如何构造 GameAccount 对象的 Account 部分。或者,换句话说,当您创建一个 GameAccount 时,您需要(作为 GameAccount 构造函数的第一部分)调用其中一个 Account 构造函数。问题是,编译器不知道要使用哪个构造函数,也不知道它使用的构造函数的参数应该是什么。所以编译器已经抱怨了。

标签: java eclipse extends


【解决方案1】:

你应该从GameAccount的构造函数的第一行调用Account的构造函数。 如果不这样做,它会尝试调用默认(无参数)构造函数,如果不存在,则会出现此编译错误。

public class GameAccount extends Account {
     public GameAccount(...) {
         super (...);
         ...
     }
}

另一种方法是在Account 中定义一个不带参数的构造函数:

public class Account {
     public Account() {
         //Code...
     }
     public Account(...) {
         //Code...
     }
}

【讨论】:

    【解决方案2】:

    这应该可以解决您的问题:

    public class GameAccount extends Account {
         public GameAccount(...) {
             super(...parameters that Account expects...);
             //Code...
         }
    }
    

    【讨论】:

      【解决方案3】:
      super(...)
      

      在 GameAccount 的构造函数中引用一个新的 Account(...)

      【讨论】:

        【解决方案4】:

        您必须在子类的构造函数中调用超类构造函数作为第一次调用:

        public GameAccount(String game, int balance) {
            super(balance);
            // Other stuff
        }
        

        【讨论】:

          猜你喜欢
          • 2014-06-20
          • 1970-01-01
          • 2019-05-08
          • 2015-01-23
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多