【问题标题】:Inheritence using this()使用 this() 继承
【发布时间】:2019-04-26 10:26:37
【问题描述】:

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

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  

提前感谢您的帮助。

【问题讨论】:

  • this问题,尤其是meriton回答的第4-5段。

标签: java inheritance constructor this multiple-inheritance


【解决方案1】:

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");
    }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-12-08
    • 1970-01-01
    • 1970-01-01
    • 2012-12-15
    • 1970-01-01
    • 1970-01-01
    • 2012-01-27
    相关资源
    最近更新 更多