gpt4 book ai didi

java - "non static method cannot be referenced from a static context"错误

转载 作者:行者123 更新时间:2023-12-02 11:10:43 25 4
gpt4 key购买 nike

这个问题在这里已经有了答案:





Cannot make a static reference to the non-static method

(8 个回答)


7年前关闭。




这是我的第一篇文章,所以格式方面的人要轻松。另外,我对 Java 也很陌生。我的程序编译器出现错误,我不知道如何修复它。我知道我必须为我的静态函数创建一个实例,但我该怎么做呢?

 import java.awt.*;
import javax.swing.*;
import java.util.*;
import java.io.*;

public class TestAccount{
public static void main (String[] args) {
Account account = new Account(1122, 20000);
Account.setAnnualInterestRate(4.5);

account.withdraw(2500);
account.deposit(3000);
System.out.println("Balance is " + account.getBalance());
System.out.println("Monthly interest is " +
account.getMonthlyInterest());
System.out.println("This account was created at " +
account.getDateCreated());
}
}

class Account {




private int id=0;
private double balance = 0;
private static double annualInterestRate = 0;
private Date dateCreated;


public Account()
{

this.id =0;
this.balance =0;
this.annualInterestRate =0;
this. dateCreated = new Date();

}

public Account(int id, double balance)
{

this.id =id;
this.balance =balance;
this. dateCreated = new Date();
}


public void setID(int id) {
this.id=id;
}

public int getID() {
return this.id;
}


public void setBalance(double balance) {
this.balance = balance;
}


public double getBalance(){
return this.balance;
}


***public static void setAnnualInterestRate(double annualInterestRate){
this.annualInterestRate = annualInterestRate;
}***


public double getAnnualInterestrate() {
return this.annualInterestRate;
}

public Date getDateCreated() {
return this.dateCreated;
}

public double getMonthlyInterest() {
return (this.annualInterestRate)/12;
}

public void withdraw(double amount) {

this.balance -=amount;
}


public void deposit(double amount)
{
this.balance += amount;
}
}

最佳答案

这里有一个问题:

   public static void setAnnualInterestRate(double annualInterestRate){
this.annualInterestRate = annualInterestRate;
}

关键字 this引用一个对象,但该方法是静态的,因此该方法无权访问单个对象。删除 this关键词。我还建议查看 static keyword. 的含义。

关于java - "non static method cannot be referenced from a static context"错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29529567/

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