【问题标题】:Constructor in Abstract method [duplicate]抽象方法中的构造函数[重复]
【发布时间】:2016-05-04 21:03:35
【问题描述】:

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

来自 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

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

【问题讨论】:

  • 我不知道你为什么说它是重复的..我只是问我的麻烦。

标签: java


【解决方案1】:

它是供具体子类使用的。

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

【讨论】:

    猜你喜欢
    • 2011-03-16
    • 2023-03-13
    • 2020-06-18
    • 1970-01-01
    • 1970-01-01
    • 2011-07-21
    • 2021-11-24
    相关资源
    最近更新 更多