Java中的oop子类和超类
在这里,我尝试从超类BankAccount生成一个子类BasicAccount。同时采取取款方式,取款金额不会超过当前账户中的金额
但是我仍然不明白为什么我不能在BasicAccount中访问它,即使变量在BankAccount中是私有的。你知道如何在我的取款方法中通过保持余额字段的私有性来访问余额吗
/**
A bank account has a balance that can be changed by
deposits and withdrawals.
*/
class BankAccount
{
private double balance;
/**
Constructs a bank account with a zero balance.
*/
public BankAccount()
{
balance = 0;
}
/**
Constructs a bank account with a given balance.
@param initialBalance the initial balance
*/
public BankAccount(double initialBalance)
{
balance = initialBalance;
}
/**
Deposits money into the bank account.
@param amount the amount to deposit
*/
public void deposit(double amount)
{
double newBalance = balance + amount;
balance = newBalance;
}
/**
Withdraws money from the bank account.
@param amount the amount to withdraw
*/
public void withdraw(double amount)
{
double newBalance = balance - amount;
balance = newBalance;
}
/**
Gets the current balance of the bank account.
@return the current balance
*/
public double getBalance()
{
return balance;
}
}
class BasicAccount extends BankAccount{
BasicAccount(double initialBalance) {
}
public void withdraw(double amount) {
if (amount > 0 && this.balance - amount >= 0) {
super.getBalance() -= amount;
} else if (amount < 0) {
throw new IllegalArgumentException("Withdraw amount should be positive and greater than 0.");
} else {
System.out.println("Error: Withdraw amount exceeds available funds.");
}
}
}
class Main {
public static void main(String args[]) {
BankAccount account = new BasicAccount(100.00);
double balance = account.getBalance(); //expected 100.00;
account.withdraw(80.00);
balance = account.getBalance(); //expected 20.00;
account.withdraw(50.00);
balance = account.getBalance(); //expected 20.00 because the amount to withdraw is larger than the balance
}
}
# 1 楼答案
你需要打超级电话。从子类中撤回(double)
同时
这没用。不能将值减去并赋给方法,只能赋给变量。这是不合逻辑的。用我说的替换,超级。提取(金额)
同时
在BasicAccount中,你有这个。平衡,但你的意思是说超级。余额,因为这个类BasicAccount不定义余额类成员,而超级类BankAccount定义
同时
您需要调用super(initialBalance),因为现在您没有调用分配balance的超级构造函数
也(oof)
与其创建一个默认构造函数来执行与另一个相同的操作,不如删除它,因为默认情况下余额为0,或者调用另一个有用途的构造函数
现在,您的初始balance构造函数可以执行一些有用的边缘案例检查,无参数构造函数可以从中受益
# 2 楼答案
如果要从子类访问超类的字段,必须将其声明为protected而不是private。然后,您将能够使用
super.variableName
访问它也看看@Jason写了什么,他指出了其他错误