《java編程思想》復(fù)用類一章,提出基類的子對(duì)象的構(gòu)建過程是從基類“向外”進(jìn)行擴(kuò)散的。
下面通過實(shí)例進(jìn)行講解,首先看下面的代碼:
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
|
import static net.mindview.util.print.*; //《java編程思想》提供的類庫 /** * @author administrator * */ public class cat extends animal { public cat() { // todo auto-generated constructor stub print( "caretoon constructor" ); } public static void main(string[] args) { cat x = new cat(); } } class biology { biology() { // todo auto-generated constructor stub print( "art constructor" ); } } class animal extends biology { animal() { // todo auto-generated constructor stub print( "drawing constructor" ); } } |
程序運(yùn)行結(jié)果:
在這里共聲明了三個(gè)類,分別是biology, animal,cat. 繼承關(guān)系如下:
在main()
函數(shù)中,經(jīng)過單步調(diào)試可以看到,創(chuàng)建cat類型對(duì)象時(shí)候,首先需要找到cat類的父類對(duì)象,即從cat類尋找其父類animal類的構(gòu)造器,最后尋找animal的父類biology類的構(gòu)造器。
找到biology基類之后,按照下面順序,執(zhí)行各自的構(gòu)造函數(shù)
所以,最終的輸出結(jié)果,如控制臺(tái)輸出所示。
需要注意的是,即使cat類不創(chuàng)建構(gòu)造器,編譯器會(huì)創(chuàng)建默認(rèn)的構(gòu)造器。仍然會(huì)調(diào)用到基類的構(gòu)造器。輸出結(jié)果如下:
總結(jié)
以上就是這篇文章的全部?jī)?nèi)容了,希望本文的內(nèi)容對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,謝謝大家對(duì)服務(wù)器之家的支持。如果你想了解更多相關(guān)內(nèi)容請(qǐng)查看下面相關(guān)鏈接
原文鏈接:https://blog.csdn.net/yangyong0717/article/details/78386477