Java編程思想讀書筆記_第8章

來源:互聯網
上載者:User

標籤:draw   return   覆蓋   log   java   end   並且   img   動態綁定   

覆蓋私人方法

 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); //016         System.out.println(f.get());//117         Son s = new Son();18         System.out.println(s.i);//119         System.out.println(s.get());//120         System.out.println(s.get_super());//021         Son s1 = (Son)f;22         System.out.println(s1.i);//123         System.out.println(s1.get());//124         System.out.println(s1.get_super());//025     }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: 014     }15 }

如果把Father中的draw定義為private的,那麼在Test中的輸出就是Father::draw

 

 

Java編程思想讀書筆記_第8章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.