【问题标题】:Passing SuperClass constructor parameters to a SubClass?将超类构造函数参数传递给子类?
【发布时间】:2015-04-26 20:07:34
【问题描述】:

刚开始在我们的项目中实现 Super 和 Sub 类,但我在创建 Subclass 构造函数以允许不同类型的帐户但遵循与 Superclass 相同的规则时遇到了一点问题。

这是我遇到的构造函数错误。

http://i.imgur.com/C3n7MxQ.png

【问题讨论】:

  • 不像super(firstName, lastName, accountNumber, street, town, postcode)吗?

标签: inheritance polymorphism subclass superclass


【解决方案1】:

在您的Account 类中,您指定了一个带有多个参数的构造函数:firstName、lastName、accountNumber 等。

在子类的构造函数中你必须调用超类的构造函数 -> super()

一个小例子:

class Person {
    public String name;
    /*constructor*/
    public Person(String name) {
        this.name = name;
    }
}

class Student extends Person {
    public String studentNumber;
    /*constructor*/
    public Student(String name, String studentNumber) {
        /* invoke super constructor. The parameters have to match the 
         * parameters specified in the constructor of Person
         */
        super(name);
        /* Now set the properties that only belongs to Student */
        this.studentNumber = studentNumber;
    }
}

【讨论】:

  • 啊!精彩的解释我现在理解得更好了,我的代码已经可以工作了:)这是我修改后的副本,你还提醒我如何使用(this.parameter)i.imgur.com/MIG1o94.png
  • 很高兴能帮上忙。
猜你喜欢
  • 1970-01-01
  • 2016-04-21
  • 1970-01-01
  • 1970-01-01
  • 2019-03-18
  • 1970-01-01
  • 2023-04-04
  • 2015-10-11
相关资源
最近更新 更多