在抽象类中调用构造函数

Man*_*tta 3 java oop constructor abstract-class

是否可以在抽象类中调用构造函数?

我读到这个构造函数可以通过它的一个非抽象子类来调用.但我不明白这个说法.有人可以用一个例子来解释这个吗?

Dun*_*nes 6

您可以在抽象类中定义构造函数,但不能构造该对象.但是,具体的子类可以(并且必须)调用抽象父类中定义的构造函数之一.

请考虑以下代码示例:

public abstract class Test {

    // abstract class constructor
    public Test() {
        System.out.println("foo");
    }

    // concrete sub class
    public static class SubTest extends Test {    
      // no constructor defined, but implicitly calls no-arg constructor 
      // from parent class
    }

    public static void main(String[] args) throws Exception {
        Test foo = new Test(); // Not allowed (compiler error)
        SubTest bar = new SubTest(); // allowed, prints "foo"
    }
}
Run Code Online (Sandbox Code Playgroud)