抽象类可以有构造函数吗?

如果可以,如何使用它,用于什么目的?


当前回答

是的,它可以,抽象类构造函数通常用于所有子类通用的初始化事件的超级调用

其他回答

为了实现构造函数链接,抽象类将有一个构造函数。 编译器将Super()语句保存在子类构造函数中,该语句将调用父类构造函数。如果抽象类没有构造函数,那么就违反了java规则,我们就无法实现构造函数链接。

是的,抽象类可以有构造函数。考虑一下:

abstract class Product { 
    int multiplyBy;
    public Product( int multiplyBy ) {
        this.multiplyBy = multiplyBy;
    }

    public int mutiply(int val) {
       return multiplyBy * val;
    }
}

class TimesTwo extends Product {
    public TimesTwo() {
        super(2);
    }
}

class TimesWhat extends Product {
    public TimesWhat(int what) {
        super(what);
    }
}

父类Product是抽象的,并且有一个构造函数。具体类TimesTwo有一个只硬编码值2的构造函数。具体类TimesWhat有一个构造函数,允许调用者指定值。

抽象构造函数将经常用于强制类约束或不变量,例如设置类所需的最小字段。

注意:因为在父类中没有默认(或无参数)构造函数 抽象类,在子类中使用的构造函数必须显式调用 父构造函数。

类中构造函数的作用是初始化字段,而不是“构建对象”。当您尝试创建一个抽象SuperClass的新实例时,编译器会给您一个错误。然而,我们可以继承一个抽象类Employee,并通过设置其变量来使用其构造函数(参见下面的示例)

public abstract class Employee {
  private String EmpName;
  abstract double calcSalary();

  Employee(String name) {
    this.EmpName = name;// constructor of abstract class super class
  }
}

class Manager extends Employee{
 Manager(String name) {
    super(name);// setting the name in the constructor of sub class
 }
double calcSalary() {
    return 0;
 }
}

是的,抽象类可以有构造函数。可以在抽象类中重载任意数量的构造函数。这些承包商可以用来初始化扩展抽象类的对象的初始状态。正如我们所知,我们不能创建抽象类的对象,因为对象是由“new”关键字创建的,而不是由构造函数创建的……它们只用于初始化子类对象的状态。

是的。当创建继承类的实例时,调用抽象类的构造函数。例如,下面是一个有效的Java程序。

// An abstract class with constructor
abstract class Base {
Base() { System.out.println("Base Constructor Called"); }
abstract void fun();
    }
class Derived extends Base {
Derived() { System.out.println("Derived Constructor Called"); }
void fun() { System.out.println("Derived fun() called"); }
    }

class Main {
public static void main(String args[]) { 
   Derived d = new Derived();
    }

}

这是上面代码的输出,

基本构造函数Called 派生构造函数调用

引用: 在这里输入链接描述