隐式超级构造函数未定义-Java错误
我正在使用下面的UML和一些说明来编写一个程序 我目前正在上蝴蝶课。以下是我到目前为止的情况隐式超级构造函数未定义-Java错误,java,class,object,constructor,Java,Class,Object,Constructor,我正在使用下面的UML和一些说明来编写一个程序 我目前正在上蝴蝶课。以下是我到目前为止的情况 package nuisance; import java.util.List; /** * @author brand * */ public class Butterfly extends Insect { private List<String> colors; /** * @param species */ public Bu
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;
}
包装滋扰;
导入java.util.List;
/**
*@author品牌
*
*/
公营蝴蝶及昆虫{
私有列表颜色;
/**
*@param物种
*/
公共蝴蝶(种类、颜色列表){
超级(种);
这个。颜色=颜色;
}
公共蝴蝶(蝴蝶){
这只蝴蝶=蝴蝶;
}
我遇到的问题是在第二个构造函数中,该构造函数应该基于现有的Butterfly对象初始化字段。我觉得我已经正确地编写了它,但是我得到了以下错误:
未定义隐式超级构造函数。必须显式调用另一个构造函数
我对此做了一些研究,但我似乎不知道如何解决这个问题。任何帮助都将不胜感激
提前谢谢。
此.butterfly
将无法编译,因为您没有名为butterfly
的字段(您不应该这样做)
您的副本构造函数应为:
public Butterfly(Butterfly butterfly) {
super(butterfly.getSpecies());
this.colors = new ArrayList<>(butterfly.colors); // deep copy
}
公共蝴蝶(蝴蝶蝴蝶){
super(butterfly.getSpecies());
this.colors=newarraylist(butterfly.colors);//深度复制
}
问题在于你的复制构造函数
public Butterfly(Butterfly butterfly) {
this.butterfly = butterfly;
}
将super()
作为第一行进行隐式调用。例如
public Butterfly(Butterfly butterfly) {
super();
this.butterfly = butterfly;
}
没有空的昆虫
构造函数。使用蝴蝶.getSpecies()
和蝴蝶.getColors()
来执行此
构造函数调用的复制。例如
public Butterfly(Butterfly butterfly) {
this(butterfly.getSpecies(), butterfly.getColors());
}
如果不显式调用super,则会为您调用super inserted。如果super类没有无参数构造函数,这将不起作用。此外,this.butterfly不是实例成员。这将是一个浅层副本,因为颜色列表将共享,
list
很可能是可变的。不过,浅层副本可能是ok、 所以我给你+1。@Andreas你没有错,但是OP在他们的第一个构造函数中有this.colors=colors;
。我会把副本放在那里(在那里做一次,但这只是我的意见);this.colors=new ArrayList(colors);
不确定哪一个是正确的(浅对深)但你们确实澄清了我的原始问题,我也明白为什么。真是太感谢你们了!@BrandonBischoff问自己,改变一只蝴蝶的颜色是否应该改变那只蝴蝶的颜色?如果是,你想要浅拷贝。如果不是,你想要深拷贝。