java - 使用 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
在此先感谢您的帮助。
解决方案
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");
}
}
推荐阅读
- vba - 如何找到丢失的用户窗体控件
- javascript - 如何为 Jekyll 页面加载外部脚本?
- c# - FastMember:指定的参数超出了有效值的范围。参数名称:名称
- java - 是否可以在页面加载之前填充 JSF 视图?
- jupyter - 如何安装 Jupyterhub
- server - 在 Ubuntu 上安装 Aerospike:无法启动服务器
- javascript - Chrome Extension can modify Window object but can't create new variable
- java - IntelliJ 14 - 从类路径中删除额外的 JAR
- scala - 其他栏目频率计算与探索
- docker - 单个域的多个位置的 Nginx 代理