是否有任何数据字段在未明确声明的情况下变为“静态”?

时间:2019-01-21 16:04:37

标签: java

我声明了没有“ static”修饰符的私有数据字段,但是当我从方法中调用数据字段时。编译器说,仅对“ annualInterestRate”字段中的一个数据“静态引用非静态方法”,而其他数据似乎还可以。

我也以相同的方式声明了其他数据,但是它们没有问题。但是如果是“ annualInterestRate”数据字段,则会给出错误信息。

import java.util.Date;
import java.util.Scanner;
public class Account {
    private int id;
    private double balance;
    private double annualInterestRate;
    private java.util.Date dateCreated;
    public Account() {

    }
    public Account(int id, double balance, double interestRate) {
        this.id = id;
        this.balance = balance;
        this.annualInterestRate = interestRate;
        dateCreated = new java.util.Date();
    }
    public void setId(int id) {
        this.id = id;
    }
    public int getId() {
        return id;
    }
    public void setBalance(double balance) {
        this.balance = balance;
    }
    public double getBalance() {
        return balance;
    }
    public void setInterestRate(double annualInterestRate) {
        this.annualInterestRate = annualInterestRate;
    }
    public double getInterestRate() {
        return annualInterestRate;
    }
    public java.util.Date getDate(){
        return dateCreated;
    }
    public double getMonthlyInterestRate() {
    double  monthlyInterestRate = annualInterestRate/12.0;
        return monthlyInterestRate;
    }
    public double getmonthlyInterest() {
        double monthlyInterestRate = annualInterestRate/12.0;
        return monthlyInterestRate*balance;
    }
    public void withdraw(double balance) {
        this.balance-=balance;
    }
    public void deposit(double balance) {
        this.balance+=balance;
    }
    public static void main(String[] args) {
        // TODO Auto-generated method stub
        int id;
        double balance,interestRate,mir;
        Scanner in = new Scanner(System.in);
        id = in.nextInt();
        balance = in.nextDouble();
        interestRate = in.nextDouble();
        Account Person = new Account(id, balance, interestRate);
        Person.withdraw(2500.0);
        Person.deposit(3000.0);
        mir = getmonthlyInterest();
        System.out.println(balance + " " + mir + " " + dateCreated);

    }

}

预计运行平稳

1 个答案:

答案 0 :(得分:1)

稍微修改您的主要方法以使用您的Account类的实例:

public static void main(String[] args) {
        // TODO Auto-generated method stub
        int id;
        double balance,interestRate,mir;
        Scanner in = new Scanner(System.in);
        id = in.nextInt();
        balance = in.nextDouble();
        interestRate = in.nextDouble();
        Account myPerson = new Account(id, balance, interestRate);
        myPerson.withdraw(2500.0);
        myPerson.deposit(3000.0);
        mir = myPerson.getmonthlyInterest();
        System.out.println(balance + " " + mir + " " + myPerson.getDate());

    }