【问题标题】:How can I use polymorphism to make a method that instantiates objects and then fill an ArrayList with them efficiently?如何使用多态性来创建实例化对象的方法,然后用它们有效地填充 ArrayList?
【发布时间】:2014-09-20 04:37:02
【问题描述】:

我有一个任务需要我编写几个类,现在我终于编写了包含 main 方法的类。以下是该课程的说明:


对于 AccountDriver 类,创建:

  1. 这个类的文件名应该是:AccountDriver.java。
  2. main() 方法。
  3. 一个 ArrayList,用于存储 Savings 或 Checking 类的 10 个对象。使用 2% (.02) 储蓄账户利率。使用帐号 100 到 109。使用初始余额 1000 到
  4. 一个名为 buildSavings() 的方法,它通过使用来实例化 Savings 对象 多态性。这个方法应该创建一个新的 Savings 对象并填写相应的数据 通过使用构造函数调用。对象的类型应该是 Account 类型,但它们应该是 实例化为 Savings(多态)类型。
  5. 想想应该如何测试它。设计测试数据,彻底测试系统的功能 类和继承层次结构。您至少应该测试 5 个对象实例化。
  6. 实例化后,此方法应将储蓄帐户存储在上面创建的 ArrayList 中。 按升序存储储蓄账户。

我已经编写了 Account、Checking 和 Savings 类,它们都有两个构造函数,包括默认值(我写出来的)。支票和储蓄都可以扩展帐户。 Account 有两个受保护的值,accountNum(int) 和 accountBal(double)。 Savings 添加了一个名为 interestRate 的私有 double。 Account 和 Savings 的值具有 getter 和 setter。 Checking 和 Savings 有 @Override(对我来说是一个新概念)toString 方法。它们是简单的类,真的。

现在我遇到了这个 AccountDriver 类的问题,因为我应该做的所有事情都是新的。

我想从创建 buildSavings() 方法开始,但是关于创建类型为 Account 但实例化为 Savings 的对象的说明真的很奇怪。我以前从来没有这样做过,我不明白我应该怎么写 - 也许使用 instanceOf ?这对我来说也是新事物。

我也很困惑,需要放入 Savings 对象的所有信息都包含在 ArrayList 指令中,所以我只是写了这个:

ArrayList<Savings> savingsAccount = new ArrayList<>();

但我不认为现在是这样,因为我应该制作这个 buildSavings() 方法。那么,我会在制作 ArrayList 时调用该方法吗?还是在我创建 ArrayList 之后那样?使用 .add 将对象添加到 ArrayList 时是否使用 buildSavings() 方法?

这就是我可以为 buildSavings() 方法收集的所有内容。我显然不知道整个多态性是如何工作的,而且我的书对任何特定语法都不是很清楚。

    public Account buildSavings () {
    Savings account = new Savings (100, 0.2);

    // what will I be returning? Why can't I put a for loop here to fill up the objects?
    // The two parameters are 100 (accountNum) and 0.2 (interest rate). How do I 
    // set the account balance when the default constructor takes no parameters and
    // the instructions specify that the second contructor only take the account number and
    // interest rate as parameters?
} 

如果有人可以通过给我一个例子来澄清这些奇怪的指令,那就太好了。我也会给我的老师发邮件,但现在是周末,所以我不能真正去上班。

谢谢

【问题讨论】:

    标签: java object arraylist polymorphism subclass


    【解决方案1】:

    虽然有点模棱两可,但方向使用的复数多于单数,所以我怀疑你的老师希望你在 buildSavings 方法中创建数组。像这样的:

    ArrayList<Account> accounts = new ArrayList();
    for (int i = 100; i <= 109; ++i) {
        accounts.add(new Savings(i, 0.2));
    }
    return accounts;
    

    Savings 类满足 Account 类的所有期望,这就是为什么在需要 Account 类的任何地方都可以使用 Savings 类的原因。请注意,反之亦然的论点不成立。储蓄类有一个账户类没有的利率。 要了解有关多态性的更多信息,您可以查看 oracle's documentation 或直接在 Google 上搜索。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-11-06
      • 2018-07-30
      • 1970-01-01
      • 2015-05-17
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多