我首先学习 没有继承状态下,java成员初始化过程
class ConstructorDemo
{
public static void main(String[] args)
{
System.out.println("hello world");
Person per = new Person();
}
}
/*
类中主要有:
1. 两个成员变量,一个非静态的age , 一个静态的commonFeature
2. 三个非静态初始化块, 一个静态初始化块
3. 为两个成员变量赋值的函数 非静态age() 和 静态commonFeature()
*/
class Person
{
/*
在一个不存在继承的类中:
1.初始化static变量,执行static初始化快-->
2.初始化普通成员变量(如果有赋值语句),执行普通初始化块-->
3.构造方法
*/
{
age = 100;
System.out.println("Person: non-static initialization block 1");
// System.out.println("Person: non-static initialization block 1" + age); //报错:非法的前向引用
}
private int age = age();
private int age()
{
System.out.println("Person int age = age()" + "..." +age);
return 66;
}
{
System.out.println("Person: non-static initialization block 2" );
}
private static String commonFeature = commonFeature();
private static String commonFeature()
{
System.out.println("Person static String commonFeature = commonFeature()" +"..." +commonFeature);
return "we are person";
}
/*
构造代码块:
1.先于构造函数运行
*/
{
System.out.println( "Person: non-static initialization block 3" );
}
Person()
{
System.out.println( "Person Constructor Run ...." + age +"..." + commonFeature );
}
static
{
System.out.println( "Person: static initialization block 1" );
}
}
/*
运行结果:
1. hello world
2. Person static String commonFeature = commonFeature()...null
3. Person: static initialization block 1
4. Person: non-static initialization block 1
5. Person int age = age()...100
6. Person: non-static initialization block 2
7. Person: non-static initialization block 3
8. Person Constructor Run ....66...we are person
从上面的结果来看,我们得到以下结论:
a. 静态优先于非静态执行(包括成员变量和初始化块);
b. 静态(成员变量和初始化块)按照源代码中的顺序执行,非静态亦如此;所以2优先于3执行,
4567按顺序执行;
c. 初始化块优先于构造函数执行 ,所以8最后执行;
*/