抽象类可以有构造函数吗?
如果可以,如何使用它,用于什么目的?
抽象类可以有构造函数吗?
如果可以,如何使用它,用于什么目的?
当前回答
是的。当创建继承类的实例时,调用抽象类的构造函数。例如,下面是一个有效的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 派生构造函数调用
引用: 在这里输入链接描述
其他回答
是的,它可以,抽象类构造函数通常用于所有子类通用的初始化事件的超级调用
虽然有很多好的答案,但我还是想提出我的意见。
构造函数不构建对象。它用于初始化对象。
是的,抽象类总是有一个构造函数。如果您没有定义自己的构造函数,编译器将为Abstract类提供一个默认构造函数。 以上对所有类都适用——嵌套的、抽象的、匿名的等等。
抽象类(与接口不同)可以具有需要初始化的非最终非静态字段。您可以在抽象类中编写自己的构造函数来实现这一点。但是,在这种情况下,不会有任何默认构造函数。
public abstract class Abs{
int i;
int j;
public Abs(int i,int j){
this.i = i;
this.j = j;
System.out.println(i+" "+j);
}
}
在扩展上述抽象类时要小心,必须从每个构造函数显式地调用super。任何构造函数的第一行都调用super()。如果您没有显式地调用super(), Java将为您完成。 以下代码将无法编译:
public class Imp extends Abs{
public Imp(int i, int j,int k, int l){
System.out.println("2 arg");
}
}
你必须像下面的例子那样使用它:
public class Imp extends Abs{
public Imp(int i, int j,int k, int l){
super(i,j);
System.out.println("2 arg");
}
}
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;
}
}
类中构造函数的作用是初始化字段,而不是“构建对象”。当您尝试创建一个抽象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;
}
}
是的!抽象类可以有构造函数!
是的,当我们将一个类定义为抽象类时,它不能被实例化,但这并不意味着抽象类不能有构造函数。每个抽象类必须有一个具体的子类,该子类将实现该抽象类的抽象方法。
当我们创建任何子类的对象时,相应继承树中的所有构造函数都将以自顶向下的方式调用。同样的情况也适用于抽象类。虽然我们不能创建抽象类的对象,但是当我们创建抽象类的具体子类类的对象时,抽象类的构造函数将被自动调用。因此,我们可以在抽象类中使用构造函数。
注意:非抽象类不能有抽象方法,但抽象类可以有非抽象方法。原因类似于构造函数,不同之处在于我们可以调用super()而不是自动调用。此外,没有什么东西像抽象构造函数一样,因为它根本没有意义。