【问题标题】:Java Extending from another Class - Am I doing it Correctly? [closed]Java 从另一个类扩展 - 我做对了吗? [关闭]
【发布时间】:2015-05-09 22:38:10
【问题描述】:

我正在练习 Java,但我在网上找到的练习题似乎遇到了问题:

我需要:

  1. 扩展账户的交易类
  2. 一个整数字段 $n$ 存储交易数量
  3. 带有参数 initial_value 的构造函数将 Account 中的余额初始化为 inital_value 并将 n 初始化为 0

帐户类别:

public class Account {

    protected double balance;

    Account(double initialBalance) {
        balance = initialBalance;
    }
    public void deposit(double amount) {
        balance = balance + amount;
    }
    public void withdraw(double amount) {
        balance = balance - amount;
    }
    public double getBalance() {
        return balance;
    }
}

我的交易尝试类:

public class Transactions extends Account {

    int numOftransactions;

    public Transactions(double initialValue) {
        super.balance = initialValue;
        numOftransactions = 0;
    }
}

【问题讨论】:

  • 你有什么问题?
  • 我需要创建一个名为 Transactions 的类,其中包含上述几点,但我不确定如何正确执行 - 我已阅读所有文档但仍在苦苦挣扎
  • 至少显示一个尝试。这篇文章只是说;你能做我的(家庭)工作吗?我不相信您在阅读了有关 inheritance 的内容后无法做出可靠的尝试。
  • 另外,请在问题中而不是在 cmets 中澄清您的问题,以便阅读它的人不必浏览您的 cmets。

标签: java class inheritance constructor


【解决方案1】:

好吧,你离得不远了。您的构造函数应该调用 Account 的构造函数来初始化余额,因为这就是 Account 构造函数的用途:

public class Transactions extends Account {
    int n; //in java there's a difference between int and Integer btw
    public Transactions( double initialBalance ) {
        super( initialBalance ); //this is how you call the super class' constructor
                                 //the super class being Account
        n = 0;
    }
}

编辑: 至于改变平衡,你真的不需要把它改成受保护的。帐户已经为您提供了修改余额的方法。您只需要覆盖 Transactions 中的方法,并在将 n 递增 1 之前调用这些方法:

public class Transactions extends Account {
    ...
    //by naming the method the same name, we overwrite the one in Account
    public void deposit(double amount) {
        //first call Account's deposit
        super.deposit( amount ); //this will call Account's version of deposit
        n++;//increment n by 1
    }
}

您可以以类似的方式覆盖 Account 的所有方法,以增加每次的交易计数。

【讨论】:

  • 交易绝不能扩展账户...
  • OP 显然在学习基本概念。这应该可以用于学习目的
【解决方案2】:
  1. 不要将balance 的访问修饰符更改为protected。不需要时不要增加曝光度。
  2. 添加对超类构造函数的显式调用。 (super(initialBalance);)。现在,Java 编译器将向超类构造函数添加一个 不带参数的调用,因为您没有明确地这样做。您可能在这里遇到了错误。删除您尝试更改超类平衡的行;这是不必要的,会增加知名度。
  3. 覆盖存款和取款方法,以便增加交易。只需添加对超类方法 (super(amount);) 的调用并将 n 加一。或许还可以为 numOfTransactions 添加一个吸气剂。
  4. numOfTransactions 的访问修饰符更改为 private 而不是 package-private(默认)。

我个人也会将子类命名为 TransactionAccount 或类似地,Transactions 直觉上听起来不太正确。

【讨论】:

  • 如果我不将 Balance 的修饰符更改为 protected - 我无法再访问 balance,因为它是私有的
  • 您不希望您的其他班级能够像这样访问余额。相反,您想使用 Transactions 构造函数的参数调用超级构造函数。阅读关键字super
猜你喜欢
  • 2023-03-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-05-15
  • 2020-02-06
相关资源
最近更新 更多