我有一些我无法理解的代码,它是如何产生输出的。这是下面的代码-
代码:
class Bird {
{ System.out.print("b1 "); }
public Bird() { System.out.print("b2 "); }
}
class Raptor extends Bird {
static { System.out.print("r1 "); }
public Raptor() { System.out.print("r2 "); }
{ System.out.print("r3 "); }
static { System.out.print("r4 "); }
}
class Hawk extends Raptor {
public static void main(String[] args) {
System.out.print("pre ");
new Hawk();
System.out.println("hawk ");
}
}
输出:
r1 r4 pre b1 b2 r3 r2 hawk
问题:
我关于这段代码的具体问题是-
- 当
Hawk
类被安装时,它会导致Raptor
类被安装,因此静态代码块首先运行。但是,在打印pre
之前,静态代码应该跟在非静态代码之后。不是吗? - 那些非静态初始化 block 看起来实际上就像构造函数一样。那么,这些可以用作常规编程中的构造函数吗?
最佳答案
static code should be followed by non-static ones, before printing pre. Isn't it?
- 正在运行
Hawk.main
触发所有三个类的初始化。这是静态初始化程序运行的时间; -
pre
已打印; -
new Hawk()
触发所有三个类的实例初始化器的执行。
can these be used as constructors in regular programming?
它们最终与来自构造函数的代码一起编译成 <init>
方法。所以是的,它们类似于构造函数代码。关键区别在于它们的运行与运行哪个构造函数无关,并且在构造函数主体之前运行。
关于java - 初始化 block 的行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16984813/