java - 静态 block - 它们何时执行

标签 java

我是 Java 的新手,我想知道为什么我的静态 block 没有执行。

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

我想知道为什么我用第二个账号进去的时候没有显示“Good Morning Michelle”。

根据我所做的研究,这个静态 block 应该在每次调用类(新帐户)时执行。

对不起,真正的初学者问题。 米歇尔

最佳答案

打印“Good Morning Michelle”的静态 block 是 static initializer .当第一次引用该类时,它们每个类只运行一次。创建该类的第二个实例不会使其再次运行。

关于java - 静态 block - 它们何时执行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16324928/

相关文章:

java - 如何使用 JDBC 在文本文件中写入大量数据而不耗尽内存

java - 正则表达式错误地评估匹配

java - 杀死应用程序时 SharedPreferences 消失

java - java中的方法同步

java - 我想使用 Intent 从 MainActivity 调用 WebView Activity,我在 string-array.xml 中存储了 5 个 url

java - 覆盖等于不工作

java - 我想借助 java 程序从 azure 监视器获取 Activity 、key-vault、nsg 流日志等日志,并将它们发送到 tcp/http 端点

java - 通过 CLI : Could not find or load main class org. testng.TestNG 执行 testng.xml 时出错

java - 图像未加载到 JFrame 内的 JPanel 中

java - BigDecimal 格式与 DecimalFormat