
선언에 추상 키워드가 포함된 클래스를 추상 클래스라고 합니다.
예제
이 섹션에서는 추상 클래스의 예를 제공합니다. 추상 클래스를 만들려면 클래스 선언에서 클래스 키워드 앞에 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의 일반 클래스와 동일하다는 것을 알 수 있습니다. 이제 클래스는 추상 클래스이지만 여전히 3개의 필드, 7개의 메서드 및 생성자가 있습니다.
이제 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 중국어 웹사이트의 기타 관련 기사를 참조하세요!