当静态块放在程序中时,静态块是构造函数区域的本地部分吗? [英] When static block is placed in a program is static block is local part of constructor area ?

查看:56
本文介绍了当静态块放在程序中时,静态块是构造函数区域的本地部分吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

class Temp

{

int x;

{

this.x = 100;

System.out.println(Init Block);

}

Temp()

{

this(20);

System.out.println(x);

System.out.println(default);

}

Temp(int x)

{

System.out.println(x);

System.out.println(x);

}

public static void main(String ... a)

{

Temp t = new Temp();

}

}

//输出

初始版块

20

20

100

默认



为什么不输出



初始块

100

100

100

默认



我的尝试:

< br $>
class Temp

{

int x;

{

this.x = 100;

System.out.println(Init Block);

}

Temp()

{

this(20);

System.out.println(x);

System.out.println(default);

}

Temp(int z)

{

System.out.println(init block value + z);

System.out.println(构造函数值+ x);

}

public static void main(String。 ..a)

{

Temp t = new Temp();

}

}

//没有数据阴影,使用数据阴影时出现问题

class Temp
{
int x;
{
this.x=100;
System.out.println("Init Block");
}
Temp()
{
this(20);
System.out.println(x);
System.out.println("default");
}
Temp(int x)
{
System.out.println(x);
System.out.println(x);
}
public static void main(String...a)
{
Temp t = new Temp();
}
}
// output
Init block
20
20
100
default

why not output comes

init block
100
100
100
default

What I have tried:

class Temp
{
int x;
{
this.x=100;
System.out.println("Init Block");
}
Temp()
{
this(20);
System.out.println(x);
System.out.println("default");
}
Temp(int z)
{
System.out.println("init block value" +z);
System.out.println("Constructor value" +x);
}
public static void main(String...a)
{
Temp t = new Temp();
}
}
// No data shadowing, problem arises when data shadowing is used

推荐答案

您的构造函数将打印参数 x的值非实例值x。如果你想要后者,那么你需要使用这个前缀来消除歧义,因此:

Your constructor will print that value of parameter x Not instance value x. If you want the latter then you need to use the this Prefix to disambiguate it, thus:
System.out.println(this.x);


这篇关于当静态块放在程序中时,静态块是构造函数区域的本地部分吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆