簡體   English   中英

Java-在另一個實例中添加抽象類的實例

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM