在宣告中包含abstract關鍵字的類別稱為抽象類別。
範例
本節為您提供了抽象類別的範例。要建立抽象類,只需在類別聲明中的 class 關鍵字之前使用abstract 關鍵字即可。
/* File name : Employee.java */ public abstract class Employee { private String name; private String address; private int number; public Employee(String name, String address, int number) { System.out.println("Constructing an Employee"); this.name = name; this.address = address; this.number = number; } public double computePay() { System.out.println("Inside Employee computePay"); return 0.0; } public void mailCheck() { System.out.println("Mailing a check to " + this.name + " " + this.address); } public String toString() { return name + " " + address + " " + number; } public String getName() { return name; } public String getAddress() { return address; } public void setAddress(String newAddress) { address = newAddress; } public int getNumber() { return number; } }
您可以觀察到,除了抽象方法之外,Employee 類別與 Java 中的普通類別相同。這個類別現在是抽象的,但它仍然具有三個欄位、七個方法和一個建構函數。
現在您可以嘗試透過以下方式實例化 Employee 類別 -
/* File name : AbstractDemo.java */ public class AbstractDemo { public static void main(String [] args) { /* Following is not allowed and would raise error */ Employee e = new Employee("George W.", "Houston, TX", 43); System.out.println("\n Call mailCheck using Employee reference--"); e.mailCheck(); } }
#當你編譯上面的類別時,它會給出以下錯誤 -
Employee.java:46: Employee is abstract; cannot be instantiated Employee e = new Employee("George W.", "Houston, TX", 43); ^ 1 error#
以上是在Java中的抽象類別的詳細內容。更多資訊請關注PHP中文網其他相關文章!