1

If we have a User base class with properties username and password.

And a child class SpecialUser, with an extra property special.

I know I can declare ArrayList<User> users = new ArrayList<User>(); and then add SpecialUser object to users, but I can only access the properties inherited from base class (username and password) that way.

Is there a way to add a SpecialUser to the ArrayList and be able to access special property? Or should they be stored seperately?

Kind regards

not an alien
  • 651
  • 4
  • 13

2 Answers2

4

Sure, you absolutely can!

Just after you get the object, cast it to SpecialUser:

SpecialUser spUser = (SpecialUser) users.get(0);

If you are not sure if the User is SpecialUser, test it before:

if (users.get(0) instanceof SpecialUser) {
    SpecialUser spUser = (SpecialUser) users.get(0);
    // ....
}
Rafael Paulino
  • 570
  • 2
  • 9
0

If you really have to, you can do it with instanceof:

User user = users.get(0);
if (user instanceof SpecialUser) {
    SpecialUser sUser = (SpecialUser) user; // class casting
    sUser.getSpecial(); // whatever subclass call you need
}

Do you really need this? Good polymorphism is about using the User -s methods and do something special in the subclasses.

Usually we prefer code without instanceof. But sometimes this is the right choice. It depends on your actual problem.

Tamas Rev
  • 7,008
  • 5
  • 32
  • 49