"非静态方法不能从静态上下文引用"错误

时间:2015-04-09 04:07:09

标签: java compiler-errors

这是我的第一篇文章,所以在格式化人员上轻松一点。另外,我对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;
    }
}

1 个答案:

答案 0 :(得分:0)

这里有一个问题:

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

关键字this是指对象,但该方法是静态的,因此该方法无法访问单个对象。删除this关键字。我还建议您查看static keyword.

的含义