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

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


当前回答

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

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

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,你可以在抽象类的构造函数中传递值,据我所知,它必须是你的方法或构造函数中的第一个语句。

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

是的,就像其他课程一样。它可以有一个构造函数,在为基类创建对象后调用它。

是的。当创建继承类的实例时,调用抽象类的构造函数。例如,下面是一个有效的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 派生构造函数调用

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