1 package interfaces.music; 2 abstract class Base{ 3 Base(){ 4 print(); 5 } 6 public abstract void print(); 7 } 8 class Derived extends Base{ 9 private int i = 1; 10 public void print() { 11 System.out.println(i); 12 } 13 } 14 public class E03_Initialization { 15 public static void main(String[] args) { 16 Derived d = new Derived(); 17 d.print(); 18 } 19 }
首先尋找main函數,進入main函數;函數
執行 Derived d = new Derived();spa
加載 class Derived extends Base,發現有一個父類;code
加載父類Base;blog
父類Base有個一構造函數,執行構造函數;it
構造函數中有個print方法,此方法被子類print方法覆蓋,但此時子類方法中 i=1 未被加載,所以系統默認給 i 賦值爲0,故此時會執行子類print方法,打印出 0;io
加載子類Derived;class
執行d.print,打印出 1;構造函數