markzzz
markzzz

Reputation: 47945

Java - Add an instance of an abstract class in another instance

I have this piece of code :

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

the point (2) fails, because it said that im about to adding a child to this container, but it is owner already by a container...

In fact, if i do this :

ILabel label=new ILabel();
profilo_2.add(label);

it said to me that ILabel() is abract and cannot be instantiated!

How can I fix it? Cheers to everybody :)

Upvotes: 0

Views: 414

Answers (4)

Flavio
Flavio

Reputation: 11977

Guessing wildly, since this depends on your code... Try this (moreless what Piotr said)

profilo_2.add(profilo_2.createButton());

Upvotes: 1

Piotr
Piotr

Reputation: 4963

The problem is probably that when you create a button with "this.createButton", that button has its parent set to "this" (in this context), and when you try to add it to profilo_2, it throws an error. Instead you should createButton on profilo_2 directly, then the parent will be the correct one (and perhaps you won´t have to add() it either?)

Upvotes: 1

robev
robev

Reputation: 1949

Try changing to

Button button2 = this.createButton();
button2.setLabel("EDIT");
profilo_2.add(button2);

By the way this has nothing to do with abstract classes, from what I see

EDIT: Though you say that #1 "adds a button to the main class", so does that mean that createButton() does this.add(button) ? If so then you should probably change that function so that isn't done every time you create a button.

Upvotes: 1

khachik
khachik

Reputation: 28693

Probably, setLabel() returns something which cannot be passed to Container::add(..). Please provide your code for Container

Upvotes: 0

Related Questions