Java中构造函数执行顺序的问题

转自:http://www.cnblogs.com/hdk1993/p/4867303.html


1,  先执行内部静态对象的构造函数,如果有多个按定义的先后顺序执行;而且静态类的构造函数只会被执行一次,只在其第一个对象创建时调用,即便是创建了同一个类的多个对象,例如main()函数里b1,b2创建了同一个类的两个对象,但是grandmaMotherClass的构造函数只被执行了一次

2,  再执行父类的构造函数(c++中如果有多个,可按照左右先后顺序执行)

3,  再执行内部普通对象的构造函数

4,  最后执行该类本身的构造函数

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
class  grandpaClass{ //
 
     public  grandpaClass(){
 
        System.out.println( "1912年 爷爷 出生了" );
 
     }
 
}
 
  
 
class  fatherClass extends  grandpaClass{
 
     public  fatherClass(){
 
        System.out.println( "1956年 爸爸 出生了" );
 
     }
 
}
 
  
 
class  grandmaMotherClass{
 
     public  grandmaMotherClass(){
 
        System.out.println( "奶奶的妈妈 是 1890年出生的" );
 
     }
 
}
 
  
 
class  gandmaClass{
 
     static  int  year = 0 ;
 
     static  grandmaMotherClassnnmm = new  grandmaMotherClass();
 
     public  gandmaClass(){
 
        year = 1911 ;
 
        System.out.println(year + "年 奶奶 出生了" );
 
     }
 
    
 
     public  gandmaClass( int  count){
 
        year += count;
 
        System.out.println(year + "年 奶奶的妹妹 出生了" );
 
     }
 
}
 
  
 
class  motherClass{
 
     public  motherClass(){
 
        System.out.println( "1957年 妈妈 出生了" );
 
     }
 
}
 
  
 
public  class  javaclass extends  fatherClass{
     /**
 
      * @param args
 
      */
 
     motherClass b = new  motherClass();;
 
     static  gandmaClass b1 = new  gandmaClass();
 
     static  gandmaClass b2 = new  gandmaClass( 2 );
 
     public  javaclass(){
 
        System.out.println( "1981年 我 出生了" );
 
     }
 
     public  static  void  main(String[] args) {
 
        // TODO Auto-generatedmethod stub
 
        System.out.println( "mainfunction is called" );
 
        javaclass my = new  javaclass();
     }
 
}
1
2
3
4
5
6
7
8
9
10
执行结果如下:
 
奶奶的妈妈 是 1890 年出生的
1911 年 奶奶 出生了
1913 年 奶奶的妹妹 出生了
main function is called
1912 年 爷爷 出生了
1956 年 爸爸 出生了
1957 年 妈妈 出生了
1981 年 我 出生了

猜你喜欢

转载自blog.csdn.net/h_025/article/details/72518003