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

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


当前回答

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

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

其他回答

抽象类可以有构造函数,但它不能被实例化。但抽象类中定义的构造函数可用于该抽象类的具体类的实例化。检查JLS组合:

如果试图使用类实例创建创建抽象类的实例,则会出现编译时错误 表达式。 抽象类的子类本身可能不是抽象的 对象的构造函数的执行 抽象类,因此,字段初始化式的执行 对于该类的实例变量。

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

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

考虑一下:

abstract class Product { 
    int value;
    public Product( int val ) {
        value= val;
    }
    abstract public int multiply();
}

class TimesTwo extends Product {
    public int mutiply() {
       return value * 2;
    }
}

超类是抽象的,并且有一个构造函数。

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

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

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

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

我想你已经得到答案了。