Java构造函数没有名字?
当我运行下面的代码时,我得到的输出为:
static block
TEst block
main block
How does the string "TEst block" gets print?它被视为构造函数吗?
public class TestBlk {
static {
System.out.println("static block");
}
{
System.out.println("TEst block");
}
public static void main(String args[]){
TestBlk blk=new TestBlk();
System.out.println("main block");
}
}
When I run the below code I am getting output as:
static block
TEst block
main block
How does the string "TEst block" gets printed? Is it considered as constructor?
public class TestBlk {
static {
System.out.println("static block");
}
{
System.out.println("TEst block");
}
public static void main(String args[]){
TestBlk blk=new TestBlk();
System.out.println("main block");
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
它是一个实例初始化程序,以及一个默认构造函数。
没有显式构造函数的类会被赋予一个合成的、公共的、无参数的构造函数。
没有调用
this()
或super()
(可能带参数)的构造函数会隐式调用super()
(不带参数) ,内部类可能会发生一些奇怪的事情)。在隐式或显式调用
super()
之后,字段初始化程序和实例初始化程序中的所有代码都会按照其在源代码中出现的顺序插入。因此,在 javac 完成代码处理后,它看起来有点像:
It's an instance initialiser, together with an default constructor.
A class without an explicit constructor, is given a synthetic, public, no-args constructor.
Constructors without a call to
this()
orsuper()
(possibly with arguments) are given an implicit call tosuper()
(without arguments, possibly something odd happens with inner classes).Immediately after an implicit or explicit call to
super()
, all the code in field initialisers and instance initialisers gets inserted in the order it appears in the source code.So after javac has finished with your code it looks a little like:
这里的内容称为:初始化块。
有两种类型的初始化块:
非静态初始化块。
<代码>{
System.out.println("测试块");
}
静态初始化块。
<代码>静态
{
System.out.println("静态块");
}
的解释:
What you have here is called: initialization block.
There are two types of initialization blocks:
Non static initialization block.
{
System.out.println("TEst block");
}
Static initialization block.
static
{
System.out.println("static block");
}
More specific, I like the explanation from here:
当您调用
new TestBlk()
时,它会作为对象构造的一部分被调用。It is called as a part of object construction when you call
new TestBlk()
.这是一个初始化块。请参阅我的对另一个问题的回答。
That's an initialization block. See my answer to this other question.