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

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


当前回答

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

其他回答

是的。当创建继承类的实例时,调用抽象类的构造函数。例如,下面是一个有效的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 class Product { 
    int value;
    public Product( int val ) {
        value= val;
    }
    abstract public int multiply();
}

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

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

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

在具体类中,具体类型Fnord的构造函数声明有效地公开了两件事:

一种代码可以请求创建Fnord实例的方法 一种方法,通过这种方法,正在构造中的派生自Fnord的类型实例可以请求初始化所有基类特性。

虽然应该有一种方法可以分别控制这两种能力,但对于每一种具体类型,都有一个定义可以同时实现这两种能力。尽管第一个能力对抽象类没有意义,但第二个能力对抽象类和其他类一样有意义,因此它的声明是必要和有用的。

正如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
   }
}