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

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


当前回答

它不仅可以,而且总是这样。如果你没有指定一个,那么它就有一个默认的无参数构造函数,就像任何其他类一样。事实上,所有的类,包括嵌套类和匿名类,如果没有指定一个默认构造函数,就会得到一个默认构造函数(在匿名类的情况下,不可能指定一个,所以您总是会得到默认构造函数)。

具有构造函数的抽象类的一个很好的例子是Calendar类。您可以通过调用Calendar. getinstance()来获得Calendar对象,但它也有受保护的构造函数。它的构造函数被保护的原因是,只有它的子类才能调用它们(或者同一个包中的类,但因为它是抽象的,所以不适用)。GregorianCalendar是一个扩展Calendar的类的例子。

其他回答

是的,抽象类可以有构造函数!

下面是一个在抽象类中使用构造函数的例子:

abstract class Figure { 

    double dim1;        
    double dim2; 

    Figure(double a, double b) {         
        dim1 = a;         
        dim2 = b;         
    }

    // area is now an abstract method 

   abstract double area(); 

}


class Rectangle extends Figure { 
    Rectangle(double a, double b) { 
        super(a, b); 
    } 
    // override area for rectangle 
    double area() { 
        System.out.println("Inside Area for Rectangle."); 
        return dim1 * dim2; 
    } 
}

class Triangle extends Figure { 
    Triangle(double a, double b) { 
        super(a, b); 
    } 
    // override area for right triangle 
    double area() { 
        System.out.println("Inside Area for Triangle."); 
        return dim1 * dim2 / 2; 
    } 
}

class AbstractAreas { 
    public static void main(String args[]) { 
        // Figure f = new Figure(10, 10); // illegal now 
        Rectangle r = new Rectangle(9, 5); 
        Triangle t = new Triangle(10, 8); 
        Figure figref; // this is OK, no object is created 
        figref = r; 
        System.out.println("Area is " + figref.area()); 
        figref = t; 
        System.out.println("Area is " + figref.area()); 
    } 
}

我想你已经得到答案了。

一个抽象类可以有一个构造函数,但是你不能创建一个抽象类的对象,那么你如何使用那个构造函数呢?

问题是,当你在子类中继承抽象类时,你可以通过子类中的super(value)方法将值传递给它的(抽象的)构造函数,不,你不继承构造函数。

所以使用super,你可以在抽象类的构造函数中传递值,据我所知,它必须是你的方法或构造函数中的第一个语句。

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

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;
 }
}

由于抽象类可以拥有所有访问修饰符的变量,因此必须将它们初始化为默认值,因此构造函数是必要的。 在实例化子类时,将调用抽象类的构造函数并初始化变量。

相反,接口只包含常量变量意味着它们已经初始化。所以接口不需要构造函数。