我的代码无法编译。我该如何解决错误?
import java.util.*;
public class BankAccount{
private double balance;
public BankAccount(double b) {
balance = b;
}
public double getBalance(){
return balance;
}
public void deposit(double d){
balance += d;
}
public boolean withdraw(double d){
if(d > balance){
return false;
} else {
balance -= d;
return true;
}
}
public class SavingsAccount extends BankAccount{
private double interest;
public SavingsAccount(double k, double inRate){
super(k);
interest = inRate;
}
public void gainInterest(){
super.getBalance() = super.getBalance() * interest;
}
}
public static void main(String[] args) {
SavingsAccount test = new SavingsAccount(1000, .05);
test.gainInterest();
System.out.println(test.getBalance());
}
以下错误
我收到了意外的类型错误 super.getBalance()= super.getBalance()* interest; 和"非静态变量,这不能从静态上下文中引用"在 SavingsAccount test = new SavingsAccount(1000,.05);
答案 0 :(得分:3)
您无法为方法分配值。
您需要将结果分配给变量或将结果传递给另一个方法,在这种情况下,您可以使用deposit
,例如......
public void gainInterest(){
deposit(super.getBalance() * interest);
}