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

更新日期:2019-07-30

997 次瀏覽

開啟你的職業生涯

透過完成課程來獲得認證

開始
廣告
© . All rights reserved.