Harry
Harry

Reputation: 109

Adding a constructor's properties to an ArrayList?

I'm trying to add a Person which has been defined within a constructor to an ArrayList so that I can then call a method which is in another class. I'm having issues with actually adding a Person to the ArrayList however. Here is what I have so far:

GrownUp class updated

public class GrownUp extends Person
{
    ArrayList<Person> people;



GrownUp(int age, String name)  
{
    super(age, name);
    this.people = new ArrayList<>();        
    name = "Bill";
    age = 36;        
}  

public ArrayList<Person> getGrownUp()
{
   return people;
}

public void setGrownUp(int age, String name)
{
    //how to add a GrownUp? 
}

So what needs to be done is:

Any help is appreciated, thanks.

I previously asked a question similar ot this but was not clear in what I was asking so I've changed my question so that hopefully it makes more sense in what I'm trying to achieve. I've added a get method but I can't figure out how to do the set method. how would I relate the Person constructor to the ArrayList to add a person into it?

Upvotes: 0

Views: 112

Answers (2)

Einar
Einar

Reputation: 181

I think it's a bit strange to have the people array within the GrownUp class. Try to map it to the real world. Would it make sense to have people within a GrownUp? I would rather have that array outside and do this:

List<People> people = new ArrayList<>();
people.add(new GrownUp(25, "Alice"));
people.add(new GrownUp(36, "Bill"));
people.add(new Child(5, "Nina"));

The GrownUp class would then look like this:

public class GrownUp extends Person {

    public GrownUp(int age, String name) {
        super(age, name)
    }
}

I guess you are planning to add more properties that is specific to the GrownUp class, like Optional<DriversLicense> getDriversLicense() or similar.

Upvotes: 3

user1211
user1211

Reputation: 1515

This should help you.

public void setGrownUp(int age, String name)
{
people.add(new GrownUp(age,name));
}

Upvotes: 1

Related Questions