在其声明中包含abstract关键字的类称为abstract class。
抽象类可能包含也可能不包含抽象方法,即没有主体的方法(public void get();)
但是,如果一个类至少具有一个抽象方法,则必须将该类声明为抽象。
如果类被声明为抽象,则无法实例化。
要使用抽象类,您必须从另一个类继承它,并在其中提供抽象方法的实现。
如果继承抽象类,则必须为其中的所有抽象方法提供实现。
例
本节为您提供了抽象类的示例。要创建抽象类,只需在类声明中的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("乔治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("乔治W.-", "Houston, TX", 43); ^ 1 error