Java 中的介面如何實現抽象?


抽象是向用戶隱藏實現詳情的過程,只向用戶提供功能。換句話說,使用者瞭解物件的作用,而不是它如何作用。

由於介面中的所有方法都是抽象的,並且使用者除了方法簽名/原型之外不知道方法是如何編寫的。使用介面,可以實現(完全)抽象。

介面中的抽象

Java 中的介面是對方法原型的規範。每當你需要指導程式設計師或者訂立合同來指定一個型別的方法和欄位應該如何使用時,都可以定義一個介面。

要建立此型別的物件,需要實現此介面,為介面的所有抽象方法提供主體,並獲取實現類的物件。

希望使用介面方法的使用者只知道實現此介面及其方法的類,實現資訊對使用者完全隱藏,從而實現 100% 的抽象。

示例

 線上演示

interface Person{
   void dsplay();
}
class Student implements Person{
   public void dsplay() {
      System.out.println("This is display method of the Student class");
   }
}
class Lecturer implements Person{
   public void dsplay() {
      System.out.println("This is display method of the Lecturer class");
   }
}
public class AbstractionExample{
   public static void main(String args[]) {
      Person person1 = new Student();
      person1.dsplay();
      Person person2 = new Lecturer();
      person2.dsplay();
   }
}

輸出

This is display method of the Student class
This is display method of the Lecturer class

更新於: 10-Sep-2019

7K+ 瀏覽

啟動您的 事業

完成課程以獲得認證

開始學習
廣告