Java-静态变量

时间:2019-01-06 22:25:22

标签: java static

  1. 如果我想在此类内创建一个静态变量,则应该节省所有帐户的总金额。这是我做的对吗?
    只需将代码放在构造函数中即可。
    还是应该只在构造函数内部,对吗?

  2. 如何打印静态变量,以便能够对其进行检查?


public class Account {

    private static double totalBalance = 0;

    private final double INTEREST_RATE = 0.015;
    private int acctNumber;
    private double balance;
    private String name;

    public Account(String name, int acctNumber, double initialBalance) {
        this.name = name;
        this.acctNumber = acctNumber;
        this.balance = initialBalance;
        this.totalBalance += this.balance;
    }

    public Account(String name, int acctNumber) {
        this.name = name;
        this.acctNumber = acctNumber;
        this.balance = 0.0;
        this.totalBalance += this.balance;
    }

2 个答案:

答案 0 :(得分:1)

许多简单问题的代码。在类中声明字段时,最主要的是关键字static。永远记住,这些字段在该类的所有实例之间共享。换句话说,当某个实例更改静态字段的值时,它将反映在该类的所有其他实例中。这里的简单代码胜于单词:

class A {
    public static int x;
}

public class Helper {

    public static void main(String[] args) {
        A someA = new A();
        A.x = 0;

        A someOtherA = new A();
        A.x = 5;

        //uncomment next line and see what happens
        //someA.x = -55;

        System.out.println("x in someA = " + someA.x);
        System.out.println("x in someOtherA = " + someOtherA.x);
        System.out.println("x in all instances of A = " + A.x);

    }
}

编辑: 关于这个问题,我可以将静态变量放入构造函数中,试试这个:

class B{
    private static int x;
    public B(int x){
        B.x = x;
    }

    public int getX() {
        return x;
    }
}

public class Helper {

    public static void main(String[] args) {
        B bOne = new B(44);
        System.out.println(bOne.getX());

        B bTwo = new B(88);
        System.out.println(bTwo.getX());
        System.out.println(bOne.getX());

    }
}

编辑两个

这是有关注释中您的问题的示例代码:

class Acc {
    public static int noOfAccounts;
    public static double totalBalance;

    public Acc(double balance) {
        //increase the number of accounts
        Acc.noOfAccounts++;
        //add the balance to totalBalance
        Acc.totalBalance += balance;
    }
}


public class Helper {

    //test
    public static void main(String[] args) {

        Acc aOne = new Acc(15.4);
        System.out.println("Acc.noOfAccounts = " + Acc.noOfAccounts);
        System.out.println("Acc.totalBalance) = " + Acc.totalBalance);

        Acc aTwo = new Acc(100.0);
        System.out.println("Acc.noOfAccounts = " + Acc.noOfAccounts);
        System.out.println("Acc.totalBalance) = " + Acc.totalBalance);

    }
}

答案 1 :(得分:0)

解决方案摘要:

  

静态变量:

     

私有静态double totalBalance;

     

构造函数1:

     

totalBalance + = this.balance;

     

其他

     

totalBalance + =金额;

     

totalBalance-=(金额+费用);

     

totalBalance + =(this.balance * INTEREST_FEE);