Q1:看下列代码,分析输出结果?
public class Test {
static {
System.out.println("static");
}
public Test() {
System.out.println("Test");
}
public static void main(String[] args) {
Test test = new Test();
}
}
A:
static
Test
Thinking:静态代码块先于构造器执行。
Q2:看下列代码,分析输出结果?
public class Test {
static Test test1 = new Test();
static {
System.out.println("static");
}
public Test() {
System.out.println("Test");
}
public static void main(String[] args) {
Test test1 = new Test();
}
}
A:
Test
static
Test
Q:看下列代码,分析输出结果?
public class Test {
static {
System.out.println("static");
}
public Test() {
System.out.println("Test");
}
public static void main(String[] args) {
Test test1 = new Test();
}
static Test test1 = new Test();
}
A:
static
Test
Test
Thinking:静态代码块按顺序执行。
Q3:看下列代码,分析输出结果?
public class Test {
static {
System.out.println("static");
}
public Test() {
System.out.println("Test");
}
public static void main(String[] args) {
Test test1 = new Test();
Test test2 = new Test();
}
static Test test1 = new Test();
}
A:
static
Test
Test
Test
Thinking:静态代码块只在类加载的时候初始化一次,之后都不再执行。
总结:static修饰的变量在构造器之前(除非该类也是static修饰,类似Q1)按顺序初始化,而且只加载一次。
tip:笔者经验非常有限,如有错误或者描述不当的地方,请轻喷。。。。。。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)