Reputation: 1
List <Person> pers = new ArrayList<Person>();
pers.add(new Women("something1"));
pers.add(new Women("something2"));
pers.add(new Men("something1"));
pers.add(new Men("something2"));
System.out.println(pers); // prints everything
The classes Women and Men extend Person. After I store the data in my list how do I print only the Women or only the Men? Also how do I access attributes from the Women and Men?
With 2 lists works fine but I'm having trouble when I only have to use one list.
Upvotes: 0
Views: 67
Reputation: 15992
Use the instanceof
keyword.
for(Person person : pers){
if(person instanceof Women){
System.out.println("I am a woman");
int height = person.getHeight();
}
else if(person instanceof Men){
System.out.println("I am a Man");
int weight = person.getWeight();
}
}
Once you know what type of object the person is, you can call any public variables/getters/setters on that object.
Upvotes: 4