Java 静态块-何时执行

Java 静态块-何时执行,java,Java,我对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 : " + firstAccoun

我对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");

}
}
我的输出是:

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

打印“早上好Michelle”的静态块是一个。当第一次引用该类时,每个类只运行一次。创建该类的第二个实例不会导致它再次运行。

静态块在第一次加载该类时执行。这就是为什么您只看到一次输出。查看此处的更多详细信息:

静态块在初始化类中的静态字段时执行一次。删除“Static”一词会将其更改为普通的初始值设定项块,每次创建类的新实例时都会执行该初始值设定项块。查看相关问题,有大量相关信息。