简体   繁体   English

双构造函数代码块,Java中的静态代码块

[英]Double Constructor Code Blocks, Static code block in Java

I stumbled upon this block of java code that seems to defy the syntax rules: 我偶然发现了这段似乎违反语法规则的Java代码块:

1. public class Sequence { 
2.     Sequence() { System.out.print("c "); } 
3.     { System.out.print("y "); } 
4.     public static void main(String[] args) { 
5.         new Sequence().go(); 
6.     } 
7.     void go() { System.out.print("g "); } 
8.     static { System.out.print("x "); } 
9. }

With reference to line 3, how could an independent block of code be opened like that? 参考第3行,如何像这样打开一个独立的代码块? I tested it and it worked. 我对其进行了测试,并且效果良好。 However, the logic flows in reverse: y will be printed before c. 但是,逻辑相反:y将在c之前打印。

Also, with reference to line 8, I am not sure what this block is trying to do. 另外,参考第8行,我不确定此块试图做什么。 It seems like a class declaration. 好像是一个类声明。 In this case, shouldn't the static keyword be followed by a class name? 在这种情况下,不应在static关键字后跟类名吗?

Could someone please clarify my doubts? 有人可以澄清我的疑问吗? Thank you. 谢谢。

The code in line number 8 is called static initialization block. 第8行中的代码称为静态初始化块。 Where as the code in line 3 is called non-static initialization block. 其中,第3行中的代码称为非静态初始化块。

static initialization blocks gets executed first. 静态初始化块将首先执行。 If there are multiple static initialization blocks, they get executed in the order of appearance. 如果有多个静态初始化块,则按出现顺序执行它们。 The content of the non static initializer block(or simply initializer block) gets copied into the content of every constructor. 非静态初始化程序块(或简称初始化程序块)的内容被复制到每个构造函数的内容中。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM