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

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


当前回答

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

其他回答

是的,它可以有一个构造函数,它的定义和行为就像任何其他类的构造函数一样。除了抽象类不能直接实例化,只能扩展,因此使用总是来自子类的构造函数。

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

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

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

我想你已经得到答案了。

package Test1;

public class AbstractClassConstructor {

    public AbstractClassConstructor() {
        
    }

    public static void main(String args[]) {
       Demo obj = new Test("Test of code has started");
       obj.test1();
    }
}

abstract class Demo{
    protected final String demoValue;
       
    public Demo(String testName){
        this.demoValue = testName;
    }
       
    public abstract boolean test1();
}

class Test extends Demo{
       
    public Test(String name){
        super(name);
    }

    @Override
    public boolean test1() {
       System.out.println( this.demoValue + " Demo test started");
       return true;
    }
   
}

考虑一下:

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

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

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

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