抽象类可以有构造函数吗?
如果可以,如何使用它,用于什么目的?
抽象类可以有构造函数吗?
如果可以,如何使用它,用于什么目的?
当前回答
是的,抽象类可以有构造函数!
下面是一个在抽象类中使用构造函数的例子:
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());
}
}
我想你已经得到答案了。
其他回答
考虑一下:
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;
}
}
超类是抽象的,并且有一个构造函数。
一个抽象类可以有一个构造函数,但是你不能创建一个抽象类的对象,那么你如何使用那个构造函数呢?
问题是,当你在子类中继承抽象类时,你可以通过子类中的super(value)方法将值传递给它的(抽象的)构造函数,不,你不继承构造函数。
所以使用super,你可以在抽象类的构造函数中传递值,据我所知,它必须是你的方法或构造函数中的第一个语句。
是的,抽象类可以有构造函数。可以在抽象类中重载任意数量的构造函数。这些承包商可以用来初始化扩展抽象类的对象的初始状态。正如我们所知,我们不能创建抽象类的对象,因为对象是由“new”关键字创建的,而不是由构造函数创建的……它们只用于初始化子类对象的状态。
正如javafuns在这里描述的,这是一个例子:
public abstract class TestEngine
{
private String engineId;
private String engineName;
public TestEngine(String engineId , String engineName)
{
this.engineId = engineId;
this.engineName = engineName;
}
//public gettors and settors
public abstract void scheduleTest();
}
public class JavaTestEngine extends TestEngine
{
private String typeName;
public JavaTestEngine(String engineId , String engineName , String typeName)
{
super(engineId , engineName);
this.typeName = typeName;
}
public void scheduleTest()
{
//do Stuff
}
}
是的,它可以有一个构造函数,它的定义和行为就像任何其他类的构造函数一样。除了抽象类不能直接实例化,只能扩展,因此使用总是来自子类的构造函数。