我有以下Java代码:
public class WeirdList {
/** The empty sequence of integers. */
/*ERROR LINE */ public static final WeirdList EMPTY = new WeirdList.EmptyList();
/** A new WeirdList whose head is HEAD and tail is TAIL. */
public WeirdList(int head, WeirdList tail) {
headActual = head;
tailActual = tail;
}
/** Returns the number of elements in the sequence that
* starts with THIS. */
public int length() {
return 1 + this.tailActual.length();
}
/** Apply FUNC.apply to every element of THIS WeirdList in
* sequence, and return a WeirdList of the resulting values. */
public WeirdList map(IntUnaryFunction func) {
return new WeirdList(func.apply(this.headActual), this.tailActual.map(func));
}
/** Print the contents of THIS WeirdList on the standard output
* (on one line, each followed by a blank). Does not print
* an end-of-line. */
public void print() {
System.out.println(this.headActual);
this.tailActual.print();
}
private int headActual;
private WeirdList tailActual;
private static class EmptyList extends WeirdList {
public int length() {
return 0;
}
public EmptyList map(IntUnaryFunction func) {
return new EmptyList();
}
public void print() {
return;
}
}
我一直得到错误:“构造函数不能应用于给定的类型”…这是否意味着超类的子类必须在构造函数中具有与超类相同数量的参数?我一直在墙上撞了一个小时.
解决方法:
子类不必具有“构造函数中与超类相同数量的参数”的任何构造函数,但它必须从其自己的构造函数中调用其某些超类构造函数.
如果超类具有no-arg构造函数,则默认情况下会调用它,如果省略对超类构造函数的显式调用,或者子类根本没有显式构造函数(就像你的情况一样),但由于你的超类没有no-arg构造函数,编译失败.
你可以在EmptyList中添加这样的东西:
private EmptyList() {
super(0, null);
}
拥有一个你的两个类继承的抽象超类也许是一个更好的主意,但这是一个选择.
标签:java
来源: https://codeday.me/bug/20190723/1508491.html