簡體   English   中英

Java-靜態變量

[英]Java - Static Variables

  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;
    }

對於很多簡單問題的代碼。 在類中聲明字段時,最主要的是關鍵字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);

    }
}

解決方案總結:

靜態變量:

私有靜態double totalBalance;

構造函數1:

totalBalance + = this.balance;

其他:

totalBalance + =金額;

totalBalance-=(金額+費用);

totalBalance + =(this.balance * INTEREST_FEE);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM