【问题标题】:java class initialize order, how it works?java类初始化顺序,它是如何工作的?
【发布时间】:2014-08-29 05:58:02
【问题描述】:
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 时没有“静态构造块”? 为什么 i 和 j 都改成默认了,而 n 还是不变?

【问题讨论】:

标签: java class initialization


【解决方案1】:

静态变量/块在它们出现时(通常)被执行/初始化。

你的输出,为什么? :

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

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

接下来,静态块执行

static construct block

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

construct block
1:  i=0  n=101initl

【讨论】:

  • 我知道你的意思,第一次创建 t1,
  • 公共静态 int i = 0;公共静态int j = i;将被执行,并且当 t2 正在创建时,这两行将不会再次执行。但是为什么当 test1 创建那两行时再次执行?(导致 i 和 j 更改为默认值)这是我不明白的。
  • public static int 行在创建 t1 或 t2 时根本不执行。因为它们是静态的,所以在加载类文件时执行。静态字段和方法与对象实例完全无关,不应链接到“实例创建时”之类的内容。
  • 当我尝试“public static int i = 3;”时,我知道当“new test(t?)” i 和 j 的 t?使用,默认值为0。感谢您的帮助!
【解决方案2】:

当这个类(它确实应该有一个大写的名字)被加载时,静态初始化器会按照它们在源代码中出现的顺序被调用。这意味着 new test("t?") 对象的创建发生在显式静态块之前。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-10-20
    • 2020-09-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多