每個類在沒有聲明構造方法的前提下,會自動生成一個不帶參數的構造方法,如果類一但聲明有構造方法,就不會產生了.證明如下:
例1:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
|
class person { person(){System.out.println( "父類-person" );} person( int z){} } class student extends person { // student(int x ,int y){super(8);} } class Rt { public static void main(String[]args) { student student_dx= new student(); //創建student類的對象 } } //輸出結果:父類-person |
例2:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
|
class person { person(){System.out.println( "父類-person" );} person( int z){} } class student extends person { student( int x , int y){ super ( 8 );} } class Rt { public static void main(String[]args) { student student_dx= new student( 3 , 4 ); //創建student類的對象 } } //沒有輸出結果 |
例1說明:student類自動生成student() {super();}(前提是:student類沒有聲明構造方法的前提下) 'super()'是用來調用父類的構造方法.
例2中的person()方法沒有被調用,說明student類沒有產生student(){super();}方法.這是因為student類已經聲明構造方法,默認的那個不帶參數的構造方法就不產生了.
再舉例:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
|
class person { person( int z){} } class student extends person { } class Rt { public static void main(String[]args) { student student_dx= new student(); //創建student類的對象 } } /*報錯: exercise14.java:8: 找不到符號 符號: 構造函數 person() 位置: 類 person class student extends person ^ 1 錯誤 */ |
說明:student類自動產生了一個student(){super();},但是由于person類已經聲明了構造方法,默認的那個帶參數的構造方法沒有產生.,所以報錯中提到找不到構造函數person()
感謝閱讀,希望能幫助到大家,謝謝大家對本站的支持!