1、static定义的变量和静态代码块,根据编写顺序先后执行
package com.study;
public class ClassWithStatic {
public static void main(String[] args) {
System.out.println(“public static void main(String[] args)”);
Super.getInstance();
}
}
class Super {
private static int iTest1;
private int iTest2 = 0;
static {
System.out.println(Super.class.getName() + " : static{}");
iTest1++;
}
private static Super instance = new Super();
public Super() {
System.out.println(this.getClass().getName() + " : Constuctor.");
iTest2++;
}
public static Super getInstance(){
return instance;
}
}
执行结果:
public static void main(String[] args)
com.study.Super : static{}
com.study.Super : Constuctor.
修改一下顺序
package com.study;
public class ClassWithStatic {
public static void main(String[] args) {
System.out.println(“public static void main(String[] args)”);
Super.getInstance();
}
}
class Super {
private static int iTest1;
private int iTest2 = 0;
private static Super instance = new Super();
static {
System.out.println(Super.class.getName() + " : static{}");
iTest1++;
}
public Super() {
System.out.println(this.getClass().getName() + " : Constuctor.");
iTest2++;
}
public static Super getInstance(){
return instance;
}
}
执行结果:
public static void main(String[] args)
com.study.Super : Constuctor.
com.study.Super : static{}
懒加载单例:
package com.study;
public class ClassWithStatic {
public static void main(String[] args) {
System.out.println(“public static void main(String[] args)”);
Super.getInstance();
}
}
class Super {
private static int iTest1;
private int iTest2 = 0;
static {
System.out.println(Super.class.getName() + " : static{}");
iTest1++;
}
private static Super instance ;
public Super() {
System.out.println(this.getClass().getName() + " : Constuctor.");
iTest2++;
}
public static Super getInstance(){
if(instancenull){
synchronized (Super.class){
if(instancenull){
instance = new Super();
}
}
}
return instance;
}
}
执行结果:
public static void main(String[] args)
com.study.Super : static{}
com.study.Super : Constuctor.