且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

构造函数不能应用于给定的类型?

更新时间:2022-04-17 16:22:33

子类不必有任何构造函数构造函数中的参数数量与超类相同,但 必须从其自己的构造函数中调用其某些超类'构造函数。

A subclass does not have to have any constructor with "the same number of parameters in the constructor as the superclass", but it does have to call some of its superclass' constructors from its own constructor.

如果超类有一个no-arg构造函数,默认情况下会调用它,如果省略对超类构造函数的显式调用,或者子类根本没有显式构造函数(就像你的情况一样),但是因为你的超类没有有一个no-arg构造函数,编译失败。

If the superclass has a no-arg constructor, it is called by default if an explicit call to a superclass constructor is omitted or if the subclass has no explicit constructor at all (as is your case), but since your superclass does not have a no-arg constructor, compilation fails.

你可以在你的 EmptyList 中添加这样的东西:

You could add something like this to your EmptyList:

private EmptyList() {
    super(0, null);
}

拥有一个抽象的超类同时也是一个更好的主意相反,类继承,但这是一个选择。

It may also be a better idea to have an abstract superclass that both of your classes inherit from, instead, but that's a choice.