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;
        }
}

而且我不断收到错误消息:“构造函数不能应用于给定类型”...这是否意味着父类(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/

相关文章:

java - 我如何加密/解密 Spring Boot 服务器属性

java - 分层边框——这在 Java Swing 中是否可行?

java - Android 中 Viewpager 的静态内容

java - 如何获取当前 View 属性?

java - 使用 (.matches) boolean 语句可以防止 XSS 攻击吗?

java - JAVA 中的符号扩展、位移位。帮助理解 C 代码位

java - Perforce Java API 行结束样式

java - 运行时异常 : Unexpected global[] in Drools

java - Elasticsearch:按字母顺序排序,忽略数字和特殊字符

java - 为什么 jHipster 使用 oracle 12c 配置?使用oracle 11g配置有什么问题吗?