java基础---java成员初始化过程

来源:互联网 发布:知乎 股份 腾讯 编辑:程序博客网 时间:2024/06/16 19:44

我首先学习 没有继承状态下,java成员初始化过程

class ConstructorDemo {public static void main(String[] args) {System.out.println("hello world");Person per = new Person();}}/*类中主要有:1. 两个成员变量,一个非静态的age , 一个静态的commonFeature2. 三个非静态初始化块, 一个静态初始化块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 world2. Person static String commonFeature = commonFeature()...null3. Person: static initialization block 14. Person: non-static initialization block 15. Person int age = age()...1006. Person: non-static initialization block 27. Person: non-static initialization block 38. Person Constructor  Run ....66...we are person从上面的结果来看,我们得到以下结论:a. 静态优先于非静态执行(包括成员变量和初始化块);b. 静态(成员变量和初始化块)按照源代码中的顺序执行,非静态亦如此;所以2优先于3执行,   4567按顺序执行;c. 初始化块优先于构造函数执行 ,所以8最后执行;*/


原创粉丝点击