package statics;
public class Test {
private static Test test = new Test();
public static int count1;
public static int count2 = 0;
private Test(){
count1++;
count2++;
}
public static Test getInstance(){
return test;
}
public static void main(String[] args) {
/*
* 当调用一个类的方法时,首先会初始化这个类,根据Java初始化的顺序,静态的首先要执行
* 1.private static Test test = new Test(); 执行构造方法,然后count1和count2的值都是1
* 2.public static int count1; 对count1的声明,并未对其再复制,count1 的值依然是1
* 3.public static int count2 = 0; 对count2进行赋值操作,所以count2 的值变成0
*/
Test test = Test.getInstance();
System.out.println("count1 : " + test.count1);// 输出 count1 : 1
System.out.println("count2 : " + test.count2);// 输出 count2 : 0
}
}
package statics;
public class Test2 {
public static void main(String[] args) {
new Child();//输出顺序是什么
/*
* 在Java中,静态部分永远是最先执行,实例化子类时,发现有父类,那父类中静态部分先执行,然后执行子类中静态部分
* 在执行子类不带参数的构造方法前,要先执行父类的不带参数的构造方法
* 输出结果:
* parent static block
* child static block
* parent constructor
* child constructor
*/
}
}
class Parent{
static String name = "hello";
static{
System.out.println("parent static block");
}
public Parent(){
System.out.println("parent constructor");
}
}
class Child extends Parent{
static String childName = "world";
static{
System.out.println("child static block");
}
public Child() {
System.out.println("child constructor");
}
}