是否可以在抽象类中调用构造函数?
我读到可以通过其非抽象子类之一调用此构造函数。但我不明白这种说法。谁能举个例子解释一下?
最佳答案
您可以在抽象类中定义构造函数,但不能构造该对象。但是,具体的子类可以(而且必须)调用抽象父类中定义的构造函数之一。
考虑以下代码示例:
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"
}
}
关于java - 在抽象类中调用构造函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24300773/