子類對父類構造方法調用小結
1、若是父類中沒有構造函數,即便用默認的構造函數,那子類的構造函數會自動調用父類的構造函數
Java代碼
- class Father {
- private int a, b;
-
- void show() {
- System.out.println(a);
- }
- }
-
- class Son extends Father {
- private int c, d;
-
- Son(int c, int d) {
- this.c = c;
- this.d = d;
- }
- }
-
- public class ConstructionTest {
- public static void main(String args[]) {
- Son s = new Son(2, 3);
- s.show();
- }
- }
輸出結果0,說明子類的構造函數自動調用父類的無參構造函數,初始化父類的成員爲0
2、若是父類中定義了無參構造函數,子類的構造函數會自動調用父類的構造函數
Java代碼
- class Father {
- private int a, b;
-
- Father() {
- System.out.println("father done");
- }
-
- void show() {
- System.out.println(a);
- }
- }
-
- class Son extends Father {
- private int c, d;
-
- Son(int c, int d) {
- this.c = c;
- this.d = d;
- }
- }
-
- public class ConstructionTest {
- public static void main(String args[]) {
- Son s = new Son(2, 3);
- s.show();
- }
- }
- 輸出結果:father done
-
- 0
- 說明重寫了默認的無參構造函數,子類自動調用這個函數,父類的成員仍是被初始化爲0.
-
- 3、 若是定義了有參構造函數,則不會有默認無參構造函數,這樣的話子類在調用父類的無參構造函數的時候會出錯(沒有用super調用父類有參構造函數的狀況下)
-
- class Father {
- private int a, b;
-
- Father(int a, int b) {
- this.a = a;
- this.b = b;
- }
-
- void show() {
- System.out.println(a);
- }
- }
-
- class Son extends Father {
- private int c, d;
-
- Son(int c, int d) {
- this.c = c;
- this.d = d;
- }
- }
-
- public class ConstructionTest {
- public static void main(String args[]) {
- Son s = new Son(2, 3);
- s.show();
- }
- }
- 輸出結果:
- Exception in thread "main" java.lang.NoSuchMethodError: Father: method <init>()V
- not found
- at Son. <init>(Son.java:5)
- at ConstructionTest.main(ConstructionTest.java:6)
實際上,在子類的每個構造函數中,都會調用父類的構造函數。調用哪個構造函數,這裏分兩種狀況:
(1)不顯式的用super來指定。這種狀況下,會默認的調用無參數的構造函數。若是父類中沒有無參數的構造函數,那麼程序就會出錯,就像以上那個例子。把Father類中的那個構造函數去掉,程序就能經過編譯。若是一個類中,沒有一個構造函數,那麼編譯器就會給這個類加上一個無參構造函數。
(2)顯式的使用super來指定調用哪個構造函數。在Son類的構造函數中加上super(c,d),程序也能夠經過編譯。
另外,看以下例子:
Java代碼
- A.java
-
- class A{
-
- public A(){
-
- System.out.println("A無參數構造函數被調用");
-
- }
-
- public A(int i){
-
- System.out.println("A有參數構造函數被調用");
-
- }
-
- }
-
- B.java
-
- class B extends A{
-
- public B(){
-
- }
-
- public B(int i){
-
- }
-
- }
-
- public static void main(String[] args){
-
- new B(1);
-
- }
-
- }
這個程序打印:無參數的構造函數被打印。而不是:有參數的構造函數被打印。這說明你只要不使用super來指定,他就會默認的去調用父類無參數的構造函數。
歡迎關注本站公眾號,獲取更多信息