在面向物件概念中,並非所有類別都能描述具體物件。若類別缺乏足夠資訊描述具體物件,即為抽象類別。除無法實例化物件外,其他功能(成員變數、方法、建構子)與一般類別相同。
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 " + name + " " + address); }
// ... getter/setter ...
}
雖為抽象類別,仍擁有 3 個成員變數、7 個方法、1 個建構子。
Employee e = new Employee("George W.", "Houston, TX", 43); // 錯誤
// Employee is abstract; cannot be instantiated
透過一般方式繼承,子類別實例化時將繼承父類所有成員。
public class Salary extends Employee {
private double salary;
public Salary(String name, String address, int number, double salary) {
super(name, address, number);
setSalary(salary);
}
public void mailCheck() {
System.out.println("Within mailCheck of Salary class");
System.out.println("Mailing check to " + getName() + " with salary " + salary);
}
public double computePay() {
System.out.println("Computing salary pay for " + getName());
return salary/52;
}
// getter/setter ...
}
public class AbstractDemo {
public static void main(String[] args) {
Salary s = new Salary("Mohd Mohtashim", "Ambehta, UP", 3, 3600.00);
Employee e = new Salary("John Adams", "Boston, MA", 2, 2400.00);
System.out.println("Call mailCheck using Salary reference --");
s.mailCheck();
System.out.println("\nCall mailCheck using Employee reference--");
e.mailCheck();
}
}
Constructing an Employee Constructing an Employee Call mailCheck using Salary reference -- Within mailCheck of Salary class Mailing check to Mohd Mohtashim with salary 3600.0 Call mailCheck using Employee reference-- Within mailCheck of Salary class Mailing check to John Adams with salary 2400.0
若想設計類別包含特定方法,但具體實作由子類決定,可在父類宣告為抽象方法:
public abstract class Employee {
// ...
public abstract double computePay(); // 無方法主體,以分號結尾
// ...
}
最終必須有具體子類實作該方法,否則從祖先到子孫都無法實例化。