【问题标题】:Implicit super constructor is undefined - Java error [duplicate]隐式超级构造函数未定义 - Java 错误 [重复]
【发布时间】:2020-06-05 11:54:01
【问题描述】:

我正在使用下面的 UML 和一些指导来编写程序。

我目前正在研究蝴蝶课程。以下是我目前所拥有的。

package nuisance;

import java.util.List;

/**
 * @author brand
 *
 */
public class Butterfly extends Insect {

    private List<String> colors;

    /**
     * @param species
     */
    public Butterfly(String species, List<String> colors) {
        super(species);
        this.colors = colors;
    }

    public Butterfly(Butterfly butterfly) {
        this.butterfly = butterfly;
    }

我遇到的问题是在第二个构造函数中,它应该基于现有的蝴蝶对象初始化字段。我觉得我写得对,但我收到以下错误:

隐式超级构造函数 Insect() 未定义。必须显式调用另一个构造函数。

我对此进行了一些研究,但似乎无法弄清楚如何解决此问题。任何帮助将不胜感激!

提前谢谢你。

【问题讨论】:

  • 如果你没有明确地调用 super,你会得到一个对 super 插入的调用。如果超类没有无参数构造函数,这不起作用。 this.butterfly 也不是实例成员。

标签: java class object constructor


【解决方案1】:

this.butterfly 将无法编译,因为您没有名为 butterfly 的字段(您不应该这样做)。

您的复制构造函数应该是:

public Butterfly(Butterfly butterfly) {
    super(butterfly.getSpecies());
    this.colors = new ArrayList<>(butterfly.colors); // deep copy
}

【讨论】:

    【解决方案2】:

    问题在于您的复制构造函数,

    public Butterfly(Butterfly butterfly) {
        this.butterfly = butterfly;
    }
    

    隐式调用super() 作为第一行。喜欢,

    public Butterfly(Butterfly butterfly) {
        super();
        this.butterfly = butterfly;
    }
    

    并且没有空的Insect 构造函数。使用Butterfly.getSpecies()Butterfly.getColors() 通过this 构造函数调用执行复制。喜欢,

    public Butterfly(Butterfly butterfly) {
        this(butterfly.getSpecies(), butterfly.getColors());
    }
    

    【讨论】:

    • 这将是一个浅拷贝,因为颜色列表将被共享,并且List 很可能是可变的。不过,浅拷贝可能没问题,所以我要 +1。
    • @Andreas 你没看错,但是 OP 在他们的第一个构造函数中有this.colors = colors;。我会把副本放在哪里(在那里做一次 - 但这只是我的意见); this.colors = new ArrayList&lt;&gt;(colors);
    • 不完全确定哪个是正确的(浅与深),但你们肯定解决了我遇到的原始问题,我也明白为什么。感激不尽!
    • @BrandonBischoff 问问你自己,改变一只蝴蝶的颜色是否应该改变那只蝴蝶副本的颜色?如果是,您需要 shallow 副本。如果没有,你想要 deep 复制。
    猜你喜欢
    • 2010-11-14
    • 2013-09-28
    • 1970-01-01
    • 2014-06-26
    • 2014-10-02
    • 1970-01-01
    • 2018-06-27
    • 2013-09-20
    • 2013-02-24
    相关资源
    最近更新 更多