[英]Constructor cannot be applied to given types?
我有以下 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;
}
}
而且我不断收到错误消息:“构造函数不能应用于给定类型”......这是否意味着超类的子类在构造函数中必须与超类具有相同数量的参数? 我已经用头撞墙一个小时了。
子类不必有“相同数量的构造为超参数”任何构造函数,但它确实有一些调用其超的构造函数从自己的构造。
如果超类具有无参数构造函数,则在省略对超类构造函数的显式调用或子类根本没有显式构造函数(如您的情况)时默认调用它,但由于您的超类没有无参数构造函数,编译失败。
您可以将这样的内容添加到您的EmptyList
:
private EmptyList() {
super(0, null);
}
拥有一个您的两个类都继承自的抽象超类可能也是一个更好的主意,但这是一种选择。
您需要向 WeirdList 显式添加一个无参数构造函数,因为 EmptyList 具有默认的无参数构造函数,但它在可以调用的超类中没有构造函数。
当您调用任何方法时, call 和 callie 必须匹配参数和返回类型。 构造函数的特殊情况是,如果您不创建一个,编译器将插入一个空白的构造函数 void Weird(){} 您可以重载一个类并拥有多个构造函数,将执行的构造函数是具有相同签名的构造函数,即类型。您正在尝试的是在 LinkedList、Vector、List java 类中做一些内置于 java 的事情。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.