標籤:
</pre><pre name="code" class="java">package com.mejustdoit;public class Component1 {public Component1(int i) {// TODO Auto-generated constructor stubSystem.out.println("Component1"+i);}}package com.mejustdoit;public class Component2 {public Component2(int i) {// TODO Auto-generated constructor stubSystem.out.println("COmponent2"+i);}}package com.mejustdoit;public class Component3 {public Component3(int i) {// TODO Auto-generated constructor stubSystem.out.println("component3"+i);}}package com.mejustdoit;public class Father {Component1 c1 = new Component1(1);Component2 c2 = new Component2(2);public Father(int i) {// TODO Auto-generated constructor stubSystem.out.println("Father"+i); Component3 c3 = new Component3(3);}}package com.mejustdoit;public class Son extends Father {Component1 c1 = new Component1(4);Component2 c2 = new Component2(5);Component3 c3 = new Component3(6);public Son(int i) {super(i);System.out.println("Son");}}package com.mejustdoit;public class PlayFatherandSon {public static void main(String[] args) {new Son(69);System.out.println("8ioew");}}運行結果如下:Component11COmponent22Father69component33Component14COmponent25component36Son8ioew下面說一下過程:進入main後new Son(69);開始構造Son對象,進入Son的建構函式public Son(int i) {super(i);// TODO Auto-generated constructor stubSystem.out.println("Son");} Son(int i)中的i被賦值69,然後往下執行到super(i);(我不知道是不是進入建構函式後調用父類的構造(要麼是預設的Super()要麼是Super(參數))方法,這裡構造的父類的對象屬於子類,然後建立對象後開始初始化父類變數,輸出Component11COmponent22再初始化(執行)構造方法(是 預設的Super()要麼是Super(參數)以下內容),輸出Father69component33然後就是初始化子類的變數,輸出Component14COmponent25component36接著子類的構造方法(也就是 預設的Super()要麼是Super(參數)以下內容)輸出Son最後輸出8ioew初始化的介紹可以參考<a target=_blank href="http://blog.csdn.net/dst111188/article/details/46754075">點擊開啟連結</a>這裡有些疑惑,希望可以交流:是不是在建立對象時進入建構函式如果該類有繼承關係就根據Super()/Super(參數)進入父類構造父類構造對象完成後按照初始化方法初始化子類對象(先初始設定變數在初始化方法(包含構造方法))?
著作權聲明:本文為博主原創文章,未經博主允許不得轉載。
java含參建構函式初始化