首页 > 解决方案 > 使用 this() 继承

问题描述

我在尝试子类和承包商时遇到了一个问题,如果可能的话,我希望有人向我解释一下。

class AA {
    AA(){System.out.println("AA");}
}

class BB {
    BB() { System.out.println("BB");}
    BB(int k) { System.out.println("BB"+k);}
}

class CC extends BB {
    CC() { System.out.println("CC"); }
    CC(int k) {
        super(k);
        for (int j=0;j<5;j++) {
            System.out.print("o");
        }
    System.out.println(k);
    }
}

class DD extends CC {
    AA a3 = new AA();
    DD(int k) { super(k);}
    DD() {
        this(2);
        System.out.println("CC");
    }
}

class Program {
    public static void main(String[] a) {
        DD d = new DD();
    }
}

这打印

BB2
ooooo2
AA
CC

但我真的不明白为什么。调用 this(2) 后,程序不应该前进到 System.out.println("CC") 然后创建 AA 类的实例吗?似乎在它进入 DD() 构造器之后,它执行了一半,然后创建了 a3 然后回来继续构造器执行。

(我期待:)

BB2
ooooo2
CC
AA  

在此先感谢您的帮助。

标签: javainheritanceconstructorthismultiple-inheritance

解决方案


Java 并不像您想象的那样编译字段初始值的分配。您可能认为在构造函数调用完成后将初始值分配给字段,但事实并非如此。它实际上是在任何super();呼叫之后完成的。

所以这里有一个例子:

class Foo {
    String string = "Hello";

    Foo() {
        System.out.println("Hello World");
    }
}

这就是它将编译为:

class Foo {
    String string;

    Foo() {
        // First the constructor of the superclass must be called.
        // If you didn't call it explicitly, the compiler inserts it for you.
        super();

        // The next step is to assign the initial values to all fields.
        string = "Hello";

        // Then follows the user written code.
        System.out.println("Hello World");
    }
}

推荐阅读