I have the following Java code:
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;
}
}
And I keep getting the error: "constructor cannot be applied to given type"... Does that mean the subclass of the superclass must have the same number of parameters in the constructor as the superclass? I've been banging my head against the wall for an hour.
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.
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.
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.
You would need to add a no-arg constructor to WeirdList explicitly as EmptyList has a default no-arg constructor but it has no constructor in the superclass that it can call.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With