java的構(gòu)造函數(shù)是一個(gè)非常重要的作用,首先java里的構(gòu)造函數(shù)是可以重載的,而且因?yàn)橐彩强梢岳^承在父類的構(gòu)造函數(shù),所以在子類里,首先必然是調(diào)用父類的構(gòu)造函數(shù)。可以看下面的兩個(gè)例子來對(duì)比:
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
|
public class Test { public static void main(String args[]) { B b = new B( 100 ); } } class A { public A() { System.out.println( "A without any parameter" ); } public A( int i) { System.out.println( "A with a parameter" ); } } class B extends A { public B() { System.out.println( "B without any parameter" ); } public B( int i) { System.out.println( "B with a parameter" ); } } |
這個(gè)例子最后輸出的是
A without any parameter
B with a parameter
可以看到首先調(diào)用的是父類的構(gòu)造函數(shù),然后再是調(diào)用自己的構(gòu)造函數(shù)。但是因?yàn)檫@里的B類中的有參數(shù)的構(gòu)造函數(shù)是沒有super父類,所以導(dǎo)致它只會(huì)執(zhí)行父類的沒有參數(shù)的構(gòu)造函數(shù)。如果要讓它執(zhí)行有參數(shù)的父類的構(gòu)造函數(shù),那么就要這樣寫代碼:
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
|
public class Test { public static void main(String args[]) { B b = new B( 100 ); } } class A { public A() { System.out.println( "A without any parameter" ); } public A( int i) { System.out.println( "A with a parameter" ); } } class B extends A { public B() { System.out.println( "B without any parameter" ); } public B( int i) { super (i); //這里就是繼承自父類的有參數(shù)的構(gòu)造函數(shù) System.out.println( "B with a parameter" ); } } |
所以最后輸出的是:
A with a parameter
B with a parameter
因此,派生類必須通過super來調(diào)用父類的含有參數(shù)的構(gòu)造函數(shù)。以下再附一道題:
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
|
public class Test extends X { Y y = new Y(); Test() { System.out.print( "Z" ); } public static void main(String args[]) { new Test(); } } class X { Y b = new Y(); X() { System.out.print( "X" ); } } class Y { Y() { System.out.print( "Y" ); } } |
輸出的結(jié)果是什么?
首先我們來分析這道題:
因?yàn)槭紫瓤催@個(gè)main函數(shù),這個(gè)main函數(shù)只有一句代碼: new Test();因?yàn)榘l(fā)現(xiàn)這個(gè)Test類是繼承自X,所以首先要構(gòu)造X,那么就進(jìn)行X類的運(yùn)行 Y b = new Y(),然后我們可以看到輸出的Y,然后就是執(zhí)行X類的構(gòu)造函數(shù),輸出X;接著就是構(gòu)造Y,然后執(zhí)行Test自己的構(gòu)造函數(shù),輸出Z,所以輸出結(jié)果是YXYZ。
以上這篇關(guān)于java中構(gòu)造函數(shù)的一些知識(shí)詳解就是小編分享給大家的全部內(nèi)容了,希望能給大家一個(gè)參考,也希望大家多多支持服務(wù)器之家。