手賤百度了一下 :java里面自定義類的有參構造方法為什么不用super()
舉個例子:
class Father { Father(){print ('father');}; } class Son { Son(){print ('son')}; }
如果只是這樣,那么構造Son之前會在后台調用一下super()函數,
調用過程你看不到,但是確實執行了,結果是先father后son
但是這種時候你顯示的寫個super就沒有意義了,那么他在什么時候用呢,再舉個例子
給你舉個例子
class Father { Father(){print ('father');}; Father(int age){print ('father is'+age);}; } class Son { Son(){super(36);print ('son')}; }
這種情況下輸出的就不是father 和 son了,而是father is 36 和 son
就是說在你父類不止一個構造函數時,顯示的調用super才有意義
進行初始化是一個方面,像我這個例子里就是輸出了一些信息
其實就是按照程序運行順序先做什么后做什么,網絡視頻說的意思對,但沒解釋清楚
是不是如果子類里有構造方法或者在其他類里要調用這個子類的構造方法,就必須在這個構造方法里調用父類的構造方法?
對,調用是必須調用的,但是分顯示調用和隱式調用
拿第二個例子來說
class Son { Son(){print ('son')}; //輸出father 和 son } class Son { Son(){super();print ('son')}; //輸出father 和 son } class Son { Son(){super(36);print ('son')}; //輸出father is 36 和 son }
根據你調用的不同結果不同,但是一定會調用的
摘自:https://zhidao.baidu.com/question/279318547.html