[英]Java - Add an instance of an abstract class in another instance
我有这段代码:
public class Profile extends Container{
public Profile(String value) {
Container profilo_1 =new Container();
Container profilo_2 =new Container();
// (1) THIS ADD A BUTTON TO THE MAIN CLASS
this.createButton().setLabel("Modifica Profilo");
// (2) NOW I NEED TO ADD A BUTTON INTO THE INSTANCE OF profilo_2 BUT IT FAILS
profilo_2.add(this.createButton());
this.add(profilo_1);
this.add(profilo_2);
}
}
点(2)失败了,因为它说即时消息即将向该容器添加一个子对象,但是它已经是容器的所有者了...
实际上,如果我这样做:
ILabel label=new ILabel();
profilo_2.add(label);
它告诉我,ILabel()是abract,无法实例化!
我该如何解决? 为大家加油:)
尝试更改为
Button button2 = this.createButton();
button2.setLabel("EDIT");
profilo_2.add(button2);
顺便说一下,这与抽象类无关,据我所知
编辑 :尽管您说#1“向主类添加了一个按钮”,但这是否意味着createButton()做到了this.add(button)? 如果是这样,那么您可能应该更改该功能,这样就不会在每次创建按钮时都这样做。
问题可能是当您使用“ this.createButton”创建按钮时,该按钮的父级设置为“ this”(在此上下文中),并且当您尝试将其添加到profilo_2时,它将引发错误。 相反,您应该直接在profilo_2上创建createButton,然后父级才是正确的(也许您也不必对它进行add()吗?)
疯狂地猜测,因为这取决于您的代码...试试这个(除非Piotr说了什么)
profilo_2.add(profilo_2.createButton());
setLabel()
可能返回无法传递给Container::add(..)
。 请提供您的Container
代码
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.