java构造函数的应用场合,java – 构造函数不能应用于给定的类型?

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值