【发布时间】:2020-03-10 14:36:05
【问题描述】:
在这段代码中,我需要创建一个扩展类 basicaccount 的对象,但我收到错误消息“无法从静态上下文引用非静态变量”我能做些什么更好?
public class BankAccount {
private double balance;
public BankAccount() {
balance = 0;
}
public BankAccount(double initialBalance) {
balance = initialBalance;
}
public void deposit(double amount) {
double newBalance = balance + amount;
balance = newBalance;
}
public void withdraw(double amount) {
double newBalance = balance - amount;
balance = newBalance;
}
public double getBalance() {
return balance;
}
class BasicAccount extends BankAccount {
public BasicAccount(Double d) {
balance = d;
}
}
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
}
}
}
【问题讨论】:
-
你能标出有警告的行吗?
-
您似乎已将您的
BasicAccount类放入您的BankAccount类中,使其成为内部类。这意味着您不能在没有BankAccount的现有实例的情况下实例化BasicAccount。你可能不想那样做。避免在知道自己在做什么之前将类放在其他类中。
标签: java