Java是面向对象的一种语言,在Java对象生成的过程,涉及子类和父类的加载、静态成员变量的初始化、子类和父类对象的初始化等过程,其具体过程通过下述代码来说明。
1. class A
2. {
3. public A(String s)
4. {
5. " Constructor A");
6. }
7. }
8.
9. class B
10. {
11. public B(String s)
12. {
13. " Constructor B");
14. }
15. }
16.
17. class C
18. {
19. public C(String s)
20. {
21. " Constructor C");
22. }
23. }
24.
25. class Base
26. {
27. static A a1 = new A("a1: static");
28. new A("a2: normal");
29. public Base()
30. {
31. new A("a3: normal");
32. "Constructor Base");
33. }
34. }
35.
36. class Derived extends Base
37. {
38. static B b1 = new B("b1: static");
39. new B("b2: normal");
40. public Derived()
41. {
42. new B("b3: normal");
43. "Constructor Derived");
44. }
45. }
46.
47. public class Test {
48. static C c1 = new C("c1: static");
49. new C("c2: normal");
50. public static void main(String[] args) {
51. new C("c3: normal");
52. new Derived();
53. "end");
54. }
55. }
该段代码的执行结果为:
c1: static Constructor C
c3: normal Constructor C
a1: static Constructor A
b1: static Constructor B
a2: normal Constructor A
a3: normal Constructor A
Constructor Base
b2: normal Constructor B
b3: normal Constructor B
Constructor Derived
end
对上述执行结果进行分析,其生成过程为:
1)程序执行时,首先加载main函数所在的类Test,由于Test类包含静态成员变量c1,因此对该变量进行初始化,调用其构造函数。
2)由于c2是Test类的对象成员变量,且此处并没有初始化Test类对象,因此不需要初始化c2。
3)执行main函数。
4) main函数声明且初始化变量c3,因此调用其构造函数。
5)main函数声明且初始化变量derived,此过程可具体划分为以下步骤:
a) 加载Derived类,由于其继承自Base类,因此还需加载Base类。
b) 类加载完成后,由父类至子类,先后完成其中静态成员变量的初始化,因此先后调用a1,b1的构造函数。
c) 静态成员变量初始化后,由父类至子类,先后完成类对象的初始化。在类对象的初始化过程中,首先初始化对象成员变量,再调用构造函数。因此,在Base类,首先调用a2的构造函数,再调用Base的构造函数,在构造函数中,调用a3的构造函数;而在Derived类,首先调用b2的构造函数,再调用Derived的构造函数,在构造函数中,调用b3的构造函数。
6) 综上,完成了整个对象的初始化生成过程和程序运行。