JAVA中子類建構函式的繼承問題

來源:互聯網
上載者:User

轉自:http://blog.csdn.net/ningbowxj3/article/details/1418939

JAVA繼承中對建構函式是不繼承的。

以下是例子:

 public class FatherClass {
 public FatherClass() {
       System.out.println(100);
 }

 public FatherClass(int age) {
      System.out.println(age);
 }

}

 

public class SonClass extends FatherClass{

        public SonClass() {
         }
        public SonClass(int c) {
                 System.out.println(1234);
        }
   
 public static void main(String[] args) {

  FatherClass f = new FatherClass(28);
  SonClass s = new SonClass(66);
 
 }
}

編譯後執行結果如下是什麼呢?

分析:1. FatherClass f = new FatherClass(28);這句沒有必要解釋

2.SonClass s = new SonClass(66);執行這句時,調用

 public SonClass(int c) {
                 System.out.println(1234);
        }

在這個建構函式中,等價於

 public SonClass(int c) {

                super();//必須是第1行,否則不能編譯
                 System.out.println(1234);
        }

所以結果是    100
                         
1234

3.如果子類建構函式是這樣寫的

public SonClass(int c) {

                super(22);//必須是第1行,否則不能編譯

               //顯示調用了super後,系統就不再調用super();
                 System.out.println(1234);
        }

執行結果是   22
                         1234

總結1:建構函式不能繼承,只是調用而已。

如果父類沒有無參建構函式

建立子類時,不能編譯,除非在建構函式代碼體中第一行,必須是第一行顯示調用父類有參建構函式

如下:

SonClass (){

super(777);//顯示調用父類有參建構函式

System.out.println(66);

}

如果不顯示調用父類有參建構函式,系統會預設調用父類無參建構函式super();

但是父類中沒有無參建構函式,那它不是不能調用了。所以編譯就無法通過了。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.