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
廣告
資料結構
網路
關係資料庫管理系統
作業系統
Java
iOS
HTML
CSS
安卓
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP