当静态块放在程序中时,静态块是构造函数区域的本地部分吗? [英] When static block is placed in a program is static block is local part of constructor area ?
问题描述
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 parameterx
Not instance value x. If you want the latter then you need to use thethis
Prefix to disambiguate it, thus:
System.out.println(this.x);
这篇关于当静态块放在程序中时,静态块是构造函数区域的本地部分吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!