私は全く新しいJavaです。なぜ私のスタティックブロックが実行されていないのでしょうか?スタティックブロック - いつ実行されるのですか
public class Main {
public static void main(String[] args) {
Account firstAccount = new Account();
firstAccount.balance = 100;
Account.global = 200;
System.out.println("My Balance is : " + firstAccount.balance);
System.out.println("Global data : " + Account.global);
System.out.println("*******************");
Account secondAccount = new Account();
System.out.println("Second account balance :" + secondAccount.balance);
System.out.println("Second account global :" + Account.global);
Account.global=300;
System.out.println("Second account global :" + Account.global);
Account.add(); }
}
public class Account
{
int balance;
static int global;
void display()
{
System.out.println("Balance : " + balance);
System.out.println("Global data : " + global);
}
static // static block
{
System.out.println("Good Morning Michelle");
}
static void add()
{
System.out.println("Result of 2 + 3 " + (2+3));
System.out.println("Result of 2+3/4 " + (2+3/4));
}
public Account() {
super();
System.out.println("Constructor");
}
}
私の出力は次のようになります。私は2番目のアカウントで行った時、「グッドモーニング・ミシェル」が表示されなかった理由を知りたい
Good Morning Michelle
Constructor
My Balance is : 100
Global data : 200
*******************
Constructor
Second account balance :0
Second account global :200
Second account global :300
Result of 2 + 3 5
Result of 2+3/4 2
。
私が行った研究から、この静的ブロックは、クラスが呼び出されるたびに(新しいアカウント)実行されるべきです。
本当の初心者ご質問には申し訳ありません。 Michelle
スタティックブロックは、クラス内の静的フィールドの初期化とともに1回実行されます。 – nhahtdh
単語「静的」を削除すると、クラスの新しいインスタンスが作成されるたびに実行される通常のイニシャライザブロックに変更されます。 –
関連する質問を見ると、これに関する情報がたくさんあります。 –