基本Java程序:不能从静态上下文引用非静态方法
我是一名试图学习java基础知识的初级程序员。基本上,bank类中的printBankSummary()和AccounteInterestAllAccounts()方法给了我这个问题。代码如下:基本Java程序:不能从静态上下文引用非静态方法,java,instance,static-methods,Java,Instance,Static Methods,我是一名试图学习java基础知识的初级程序员。基本上,bank类中的printBankSummary()和AccounteInterestAllAccounts()方法给了我这个问题。代码如下: public class Bank { private String name; private SavingsAccount [] accounts; private int totalAccounts; public static final int MAX_ACCOUNTS =
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作为一个函数调用printAccountInfo()
。您基本上是在告诉Java:“您可以在SavingsAccount类中找到这个方法,而不需要SavingsAccount的实例来使用它。”
您可能要做的是查找要打印其帐户信息的类SavingsAccount
的实例。假设这个实例位于变量x
中,那么您可以调用x.printAccountInfo()
调用
AccounteInterest
时也会发生同样的情况
BankAccount.printAccountInfo();
是静态方法(从类访问),因此除非调用它的方法也是静态的,否则无法访问。
而不是
public void printBankSummary() {
System.out.println("Bank name: " + getName());
BankAccount.printAccountInfo();
}
那怎么办
public void printBankSummary() {
System.out.println("Bank name: " + getName());
//calls printAccountInfo on the instance that called printBankSummary()
printAccountInfo();
}
以及
public void accrueInterestAllAccounts() {
SavingsAccount.accrueInterest();
}
您不能调用Class.Method,您要做的是
public void accrueInterestAllAccounts() {
for(Account acc: Accountarr) {
acc.accrueInterest();
}
}
答案很简单:由于Java中静态类型的性质,任何引用静态方法/变量的方法也必须是静态的 解决方法是将类和测试程序分开,这样在类的源文件中就没有“publicstaticvoidmain(stringargs[])方法。然后,您可以将这两个给您带来麻烦的方法放在测试类中,并将它们的方法声明修改为静态
如果您确实希望您的两个有问题的方法成为实例方法,那么您需要包装一个类的新实例,并以这种方式调用它们 哪一行给出了编译器错误?行
BankAccount.printAccountInfo()代码>和保存saccount.AccounteInterest()代码>两行都在银行类中。这太多代码了。您应该删除所有与问题无关的内容。(不用说,您应该测试一个以这种方式简化的示例。)此外,请在清单中出现错误时使用注释。谢谢您的帮助。这是我第一次在这里发帖。我会记住这一点。我将代码“Bank x=new Bank account(“Java S&L”)”改为“Bank x=new SavingsAccount(“Java S&L”)。尽管如此,问题仍然存在。这就是你的意思吗?首先,Bank
和SavingsAccount
是不同的类。对于其余部分,我已经编辑了我的答案。