Java編程思想讀書筆記_第8章
阿新 • • 發佈:2017-07-16
讀書筆記 div spl class alt oid ava 函數 opened
覆蓋私有方法
1 class Father { 2 private void f() { System.out.println("Father::f()"); } 3 public static void main(String[] args) { 4 Father father = new Son(); 5 father.f(); //輸出:Father::f() 6 } 7 } 8 9 class Son extends Father { 10 public void f() { System.out.println("Son::f()"); }11 public static void main(String[] args) { 12 Son son = new Son(); 13 son.f(); //輸出:Son::f() 14 } 15 }
上面例子中由於Father的f是私有的,所以在Father的main方法中對f的調用是靜態綁定的。
如果把f定義為public的,則在Father中對f的調用將是動態綁定的。
域與靜態方法
1 class Father { 2 public int i = 0; 3 public int get() { return i; }4 } 5 6 class Son extends Father { 7 public int i = 1; 8 public int get() { return i; } 9 public int get_super() { return super.i; } 10 } 11 12 class Test { 13 public static void main(String[] args) { 14 Father f = new Son(); 15 System.out.println(f.i); //0 16 System.out.println(f.get());//117 Son s = new Son(); 18 System.out.println(s.i);//1 19 System.out.println(s.get());//1 20 System.out.println(s.get_super());//0 21 Son s1 = (Son)f; 22 System.out.println(s1.i);//1 23 System.out.println(s1.get());//1 24 System.out.println(s1.get_super());//0 25 } 26 }
對於成員函數的訪問是沒有多態的,子類型和父類型中的i是不同的存儲空間。使用父指針訪問的時候使用的父的空間,使用子指針訪問的時候使用的是子的空間。
在構造函數中調用的函數如果是可以動態綁定的,並且在子類中被繼承了,那麽就會調用子類的方法
1 class Father { 2 void draw() { System.out.println("Father::draw"); } 3 Father() { draw(); } 4 } 5 6 class Son extends Father { 7 int i = 1; 8 void draw() { System.out.println("Son::draw: " + i); } 9 } 10 11 class Test { 12 public static void main(String[] args) { 13 new Son(); //Son::draw: 0 14 } 15 }
如果把Father中的draw定義為private的,那麽在Test中的輸出就是Father::draw
Java編程思想讀書筆記_第8章