java类的初始化顺序,它是如何工作的?

标签 java class initialization

package ali;

public class test {
public static int n = 99;

public static test t1 = new test("t1");
public static test t2 = new test("t2");

public static int i = 0;
public static int j = i;
{
    System.out.println("construct block");
}

static {
    System.out.println("static construct block");
}

public test(String str){
    System.out.println((++j) + ":" + "  i="+ i + "  n="+n+str);
    n++;i++;
}

public static void main(String [] args){
    test test1 = new test("initl");
}
}

运行后:

construct block
1:  i=0  n=99t1
construct block
2:  i=1  n=100t2
static construct block
construct block
1:  i=0  n=101initl

谁能告诉我怎么用? 为什么创建 t1 和 t2 时没有“静态构造 block ”? 为什么i和j都改成默认的了,n却没变?

最佳答案

静态变量/ block 在出现时执行/初始化(通常)。

你的输出以及为什么? :

当类加载并初始化期间,将执行以下几行

public static test t1 = new test("t1");
public static test t2 = new test("t2");

这又创建了新的 Test 对象,但由于该类已经正在初始化,因此上面的代码行不会再次执行。

所以,

你得到了

construct block
1:  i=0  n=99t1
construct block
2:  i=1  n=100t2

接下来,静态 block 执行

static construct block

现在,当您在 main() 中创建 Test 对象时,您将拥有

construct block
1:  i=0  n=101initl

关于java类的初始化顺序,它是如何工作的?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25562443/

相关文章:

java - 创建连接时执行sql语句

java - 谷歌的 zxing(斑马线)条形码库的 BitMatrix 不在它应该在的地方

C++ - 高级多态性 : Is this function legal for removing pointers from a list?

ruby - Ruby 中的类静态实例初始值设定项(即工厂方法)

c - 如何在程序开始处声明

python - 如何防止动态库多次初始化

java - Java 7 SE 是否支持 EJB?

java - 从实体中获取外键引用变量在jpa中返回空列表

jquery - 使用 jQuery 通过 ID 名称查找类

java - 为什么实例和静态内部类的初始化不同?