How to store multiple different objects with the same parent class

edited June 2017 in How To...

Say I have a parent class called Bicycle, and three different classes that extend this are called BikeA, BikeB, and BikeC.

Now, I have found that I can store all of these child objects inside an ArrayList declared ArrayList<Bicycle>. When it comes to scanning through the list, though, I need to differentiate these into their respective classes. Would getClass() still work, or have they been typecasted to Bicycle? I suppose I could always put an enum in the parent class and then typecast them later, but I'd prefer to go with the former option.

Answers

  • I should probably start trying things before asking, because I answered my own question. The answer is yes, getClass() works. I was worried the child-class-specific objects would be lost, but they are not. This is great because you can make a list that can store anything in the family.

  • An object never changes the actual datatype it was born w/ new.

    However, we can momentarily change its apparent datatype by using a (cast) operator or assigning it to a variable of some compatible, but diff. datatype.

  • The answer is yes, getClass() works.

    Operator instanceof is more performant. $-)

  • and three different classes that extend this are called BikeA, BikeB, and BikeC.

    Before creating those subclasses, you should ask 1st how much they're different from their parent class. Also, how much they're diff. from each other? :-/

  • Or use interface

Sign In or Register to comment.