初始化块的行为(Behavior of Initialization Blocks)
我有我无法理解的代码,它是如何产生输出的。 以下是以下代码 -
码:
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 "); } }问题:
我对这个代码的具体问题是 -
当Hawk类被创建时,它会导致Raptor类被创建,因此静态代码块将首先运行。 但是,在打印pre ,静态代码应该跟随非静态代码。 不是吗? 那些非静态初始化块似乎实际上就像构造函数一样。 那么,这些可以在常规编程中用作构造函数吗?I have code which I am unable to understand, how it produces that output. Here is the code below-
Code:
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 "); } }Questions:
My specific questions regarding this code are-
When Hawk class is instationed, it cause Raptor class to be instationed, and hence the static code block runs first. But then, static code should be followed by non-static ones, before printing pre. Isn't it? Those non-static initialization blocks seem to be actually acting like constructors. So, can these be used as constructors in regular programming?最满意答案
运行Hawk.main触发所有三个类的初始化。 这是静态intitializers运行的时候; pre印; new Hawk()触发所有三个类的实例初始值设定项的执行。在打印前,静态代码应该跟随非静态代码。 不是吗?
这些可以在常规编程中用作构造函数吗?
它们最终与来自构造函数的代码一起编译到<init>方法中。 所以是的,它们与构造函数代码类似。 关键的区别在于,无论运行哪个构造函数,它们都会运行,并在构造函数体之前运行。
Running Hawk.main triggers the initialization of all three classes. This is when the static intitializers run; pre is printed; new Hawk() triggers the execution of instance initializers for all three classes.static code should be followed by non-static ones, before printing pre. Isn't it?
can these be used as constructors in regular programming?
They end up compiled together with code from constructors into <init> methods. So yes, they are similar to constructor code. The key difference is that they run regardless of which constructor runs, and run before the constructor body.
更多推荐
发布评论