java 中編譯時多型和執行時多型有什麼區別?


如果使用例項方法執行(實現)方法重寫和方法過載,則為執行時(動態)多型性。

在動態多型性中,方法呼叫和方法體之間的繫結發生在執行時間,此繫結稱為動態繫結或延遲繫結。

範例

實況演示

class SuperClass{
   public static void sample(){
      System.out.println("Method of the super class");
   }
}
public class RuntimePolymorphism extends SuperClass {
   public static void sample(){
      System.out.println("Method of the sub class");
   }
   public static void main(String args[]){
      SuperClass obj1 = new RuntimePolymorphism();
      RuntimePolymorphism obj2 = new RuntimePolymorphism();
      obj1.sample();
      obj2.sample();
   }
}

輸出

Method of the super class
Method of the sub class

如果使用靜態、私有、final 方法執行(實現)方法重寫和方法過載,則為編譯時(靜態)多型性。

在靜態多型性中,方法呼叫和方法體之間的繫結發生在編譯時間,此繫結稱為靜態繫結或早期繫結。

範例

class SuperClass{
   public static void sample(){
      System.out.println("Method of the super class");
   }
}
public class SubClass extends SuperClas {
   public static void sample(){
      System.out.println("Method of the sub class");
   }
   public static void main(String args[]){
      SuperClass.sample();
      SubClass.sample();
   }
}

輸出

Method of the super class
Method of the sub class

更新於: 30-7-2019

993 次觀看

事業起航

完成課程即可獲得認證

開始
廣告
© . All rights reserved.