0

I think that java will not initialize the a with four values. But I'm wrong, can you please explain me how it does this? I mean what it does when a constructor called because I'm not initialize a in constructor.

class A  {
    int[] a = {1,2,3,4};
    A() {
        a[0] = 3;
    }
}

class ClassTest1 {
    public static void main(String args[]) {
        A b = new A();

        System.out.println("hey " + b.a[0] );
        System.out.println("hey " + b.a[1] );
    }
}

If you explain in detail and with some external resource to understand internals, it could be better for a newbie(me).

4

1 回答 1

4

当你拥有int[] a = {1,2,3,4}它时,它会将该行编译到构造函数的顶部。所以你的构造函数看起来像这样:

a = {1,2,3,4};
a[0] = 3;

现在,这是对发生的事情的一个非常简单的定义。如果您有多个构造函数,您可以将其视为将其放入所有构造函数中,但您也可以将其视为仅将其放入其中一个(您实际调用的那个......)。

考虑一下:

class Counter {
    static int nextId = 0;
    static int nextId() { return nextId++; }

    final int id = nextId();
    final String name;

    public Counter() {
        this("Unnamed counter");
    }
    public Counter(String name) {
        this.name = name;
    }

}

因此,您可以选择创建一个没有名称的计数器,并且您只获得一个默认名称。现在从上面的示例中,您可以推断出您的构造函数神奇地变成了以下内容:

public Counter() {
    this.id = nextId();
    this("Unnamed counter");        
}
public Counter(String name) {
    this.id = nextId();
    this.name = name;
}

但我们知道这是不行的——它尝试id在泛型构造函数中设置,然后进入命名构造函数并尝试再次设置它。一旦设置了最终变量,您就无法设置它!

所以相反,我们可以这样想:我们实际调用的任何构造函数都会获得额外的初始化行,但可能被链接的构造函数不会获得额外的行。

于 2013-07-11T20:20:59.937 回答