抽象方法中的构造函数

时间:2016-01-27 18:36:12

标签: java

当抽象方法无法实例化时,为什么抽象方法中有构造函数?这让我感到困惑。

来自tutorialspoint.com的代码

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类,如下所示:

* 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

我遇到麻烦的是,如果必须显示错误,为什么他们的构造函数在Abstract类中出于什么原因?

1 个答案:

答案 0 :(得分:2)

可以使用具体的子类。

class SubEmployee extends Employee {
  public SubEmployee(String name, String address, int number) {
    super(name, address, number);
  }
  ...
}