抽象类可以有构造函数吗?
如果可以,如何使用它,用于什么目的?
抽象类可以有构造函数吗?
如果可以,如何使用它,用于什么目的?
当前回答
正如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
}
}
其他回答
它不仅可以,而且总是这样。如果你没有指定一个,那么它就有一个默认的无参数构造函数,就像任何其他类一样。事实上,所有的类,包括嵌套类和匿名类,如果没有指定一个默认构造函数,就会得到一个默认构造函数(在匿名类的情况下,不可能指定一个,所以您总是会得到默认构造函数)。
具有构造函数的抽象类的一个很好的例子是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;
}
}
超类是抽象的,并且有一个构造函数。
类中构造函数的作用是初始化字段,而不是“构建对象”。当您尝试创建一个抽象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;
}
}
是的,抽象类可以有构造函数!
下面是一个在抽象类中使用构造函数的例子:
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());
}
}
我想你已经得到答案了。
由于抽象类可以拥有所有访问修饰符的变量,因此必须将它们初始化为默认值,因此构造函数是必要的。 在实例化子类时,将调用抽象类的构造函数并初始化变量。
相反,接口只包含常量变量意味着它们已经初始化。所以接口不需要构造函数。