JAVA多型特性的實驗

壹頁書發表於2013-12-19
1.物件的資料成員沒有多型特性

以下實驗證明了資料成員不存在多型的特性。
如果是Base指標,就指向Base的資料成員;
如果是Derived的指標,就指向Derived的資料成員。
  1. class Base {
  2.     protected int i = 47;
  3. }

  4. class Derived extends Base {
  5.     protected int i = 27;
  6. }

  7. public class Test {
  8.     public static void main(String[] args) {
  9.         Base b = new Derived();
  10.         System.out.println(b.i);

  11.         Derived d = new Derived();
  12.         System.out.println(d.i);
  13.         
  14.         //執行結果:
  15.         //47
  16.         //27
  17.     }
  18. }
下面的例子也說明了同樣的問題

  1. class Base {
  2.     int i = 47;

  3.     int f() {
  4.         return i;
  5.     }

  6. }

  7. class Derived extends Base {
  8.     int i = 27;

  9.     int g() {
  10.         return i;
  11.     }
  12. }

  13. public class Test {
  14.     public static void main(String[] args) {
  15.         Derived d = new Derived();
  16.         System.out.println(d.f());
  17.         System.out.println(d.g());
  18.         //執行結果:
  19.         //47
            //27
  20.     }
  21. }
2.只有成員函式存在多型特性

  1. class Base {
  2.     int i = 47;

  3.     int f() {
  4.         return g();
  5.     }

  6.     int g() {
  7.         return i;
  8.     }

  9. }

  10. class Derived extends Base {
  11.     int i = 27;

  12.     int g() {
  13.         return i;
  14.     }
  15. }

  16. public class Test {
  17.     public static void main(String[] args) {
  18.         Derived d = new Derived();
  19.         System.out.println(d.f());    
  20.         //執行結果:27
  1.     }
  2. }
物件d呼叫f方法,多型特性導致f呼叫子類的g方法,而不是父類的g方法,故返回27。

3.private final方法會影響多型
    Java的多型特性依賴於晚繫結(動態、執行時繫結)
    並且Java中所有的繫結都是晚繫結
    除了final方法和private方法(private是final的一種)
    這兩種方法採用早繫結,即編譯期就確定了執行的方法。

  1. class Base {
  2.     int i = 47;

  3.     int f() {
  4.         return g();
  5.     }

  6.     private int g() {
  7.         return i;
  8.     }

  9. }

  10. class Derived extends Base {
  11.     int i = 27;

  12.     int g() {
  13.         return i;
  14.     }
  15. }

  16. public class Test {
  17.     public static void main(String[] args) {
  18.         Derived d = new Derived();
  19.         System.out.println(d.f());
  20.         //執行結果:47
  21.     }
  22. }
    因為f函式呼叫的g函式是私有的,java採用早繫結,所以沒有多型特性,直接繫結在了Base的g函式上。



來自 “ ITPUB部落格 ” ,連結:http://blog.itpub.net/29254281/viewspace-1063748/,如需轉載,請註明出處,否則將追究法律責任。

相關文章