Lớp chứa từ khóa abstract trong khai báo gọi là abstract class.
- Abstract class có thể có hoặc không có abstract method (method không có body:
public void get();). - Nhưng nếu class có ít nhất một abstract method, thì class phải khai báo
abstract. - Nếu class khai báo abstract, không thể khởi tạo (instantiate) nó.
- Để dùng abstract class, phải kế thừa từ class khác, cung cấp triển khai cho abstract method.
- Nếu kế thừa abstract class, phải cung cấp triển khai cho tất cả abstract method trong nó.
Ví dụ
Phần này cung cấp ví dụ abstract class. Tạo abstract class bằng từ khóa abstract trước class.
/* 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; }
}
Quan sát: trừ abstract method, Employee class giống class thường. Class giờ abstract, nhưng vẫn có 3 field, 7 method, 1 constructor.
Bây giờ thử khởi tạo Employee class như sau:
/* 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();
}
}
Khi compile class trên, nó cho lỗi:
Employee.java:46: Employee is abstract; cannot be instantiated
Employee e = new Employee("George W.", "Houston, TX", 43);
^
1 error