构造函数不能应用于给定的类型? [英] Constructor cannot be applied to given types?

查看:216
本文介绍了构造函数不能应用于给定的类型?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下Java代码:

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.

如果超类有一个no-arg构造函数,默认情况下会调用它,如果省略对超类构造函数的显式调用,或者子类根本没有显式构造函数(就像你的情况一样),但是因为你的超类没有有一个no-arg构造函数,编译失败。

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.

你可以在你的 EmptyList 中添加这样的东西:

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.

这篇关于构造函数不能应用于给定的类型?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆