关于java:Abstract方法中的构造函数

Constructor in Abstract method

本问题已经有最佳答案,请猛点这里访问。

当抽象方法不能实例化时,为什么抽象方法中有构造函数?我很困惑……

来自tutorialspoint.com的代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
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类,如下所示:

1
2
3
4
5
6
7
8
9
10
11
12
13
* 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("
 Call mailCheck using Employee reference--"
);
      e.mailCheck();
    }
}

编译上述类时,会出现以下错误:

1
2
3
4
   Employee.java:46: Employee is abstract; cannot be instantiated
  Employee e = new Employee("George W.","Houston, TX", 43);
               ^
1 error

我遇到的问题是,如果必须显示错误,为什么抽象类中的构造函数是出于什么原因?


它可以用于具体的子类。

1
2
3
4
5
6
class SubEmployee extends Employee {
  public SubEmployee(String name, String address, int number) {
    super(name, address, number);
  }
  ...
}