初始化块的行为(Behavior of Initialization Blocks)

编程入门 行业动态 更新时间:2024-10-27 01:32:21
初始化块的行为(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>方法中。 所以是的,它们与构造函数代码类似。 关键的区别在于,无论运行哪个构造函数,它们都会运行,并在构造函数体之前运行。

static code should be followed by non-static ones, before printing pre. Isn't it?

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.

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.

更多推荐

本文发布于:2023-04-27 11:43:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1327118.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:初始化   Behavior   Blocks   Initialization

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!