Ivana
Ivana

Reputation: 1

Java lists and class inheritance

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

Answers (2)

Jason Woo
Jason Woo

Reputation: 321

Object.getClass() will return the type of the object

Upvotes: 0

Eric Guan
Eric Guan

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

Related Questions