gpt4 book ai didi

java - 基本Java程序: non-static method cannot be referenced from a static context

转载 作者:行者123 更新时间:2023-12-01 15:06:42 27 4
gpt4 key购买 nike

我是一名初级程序员,正在尝试学习 java 的基础知识。基本上,银行类中的方法 printBankSummary() 和 accrueInterestAllAccounts() 给了我这个问题。代码如下:

public class Bank {

private String name;
private SavingsAccount [] accounts;
private int totalAccounts;
public static final int MAX_ACCOUNTS = 20;

public Bank(String name) {
this.name = name;
totalAccounts = 0;
accounts = new SavingsAccount[MAX_ACCOUNTS];
}

public void printBankSummary() {
System.out.println("Bank name: " + getName());
BankAccount.printAccountInfo(); //non-static method cannot be referenced from a static context error
}

public void accrueInterestAllAccounts() {
SavingsAccount.accrueInterest(); //non-static method cannot be referenced from a static context error
}

public static void main (String args[]) {
Bank x = new BankAccount("Java S&L");

x.printBankSummary();
x.accrueInterestAllAccounts();
}

最佳答案

这些方法是实例方法 - 它们在您的类SavingsAccount实例上运行。

当您调用 SavingsAccount.printAccountInfo() 时,您是在告诉 Java 以 static method 形式调用 printAccountInfo() 。您基本上是在告诉 Java:“您可以在 SavingsAccount 类中找到此方法,并且不需要 SavingsAccount 的实例即可使用它。”。

您可能想要做的是找到您想要打印其帐户信息的 SavingsAccount 类的实例。假设此实例位于变量 x 中,那么您将调用 x.printAccountInfo()
在调用 accrueInterest 时也会发生同样的情况。

关于java - 基本Java程序: non-static method cannot be referenced from a static context,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12867736/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com