gpt4 book ai didi

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

转载 作者:塔克拉玛干 更新时间:2023-11-01 21:56:38 24 4
gpt4 key购买 nike

我有以下 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;
}
}

而且我不断收到错误消息:“构造函数不能应用于给定类型”...这是否意味着父类(super class)的子类在构造函数中必须具有与父类(super class)相同数量的参数?我已经用头撞墙一个小时了。

最佳答案

子类不必具有任何“构造函数中的参数数量与父类(super class)相同”的构造函数,但它确实必须从其自己的构造函数中调用其父类(super class)的一些构造函数.

如果父类(super class)有一个无参数的构造函数,如果省略了对父类(super class)构造函数的显式调用,或者如果子类根本没有显式构造函数(就像你的情况),那么默认情况下会调用它,但是因为你的父类(super class)没有没有无参数构造函数,编译失败。

您可以将类似这样的内容添加到您的 EmptyList:

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

拥有一个您的两个类都继承自的抽象父类(super class)可能也是一个更好的主意,但这是一个选择。

关于java - 构造函数不能应用于给定类型?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19074568/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com