• Post Reply Bookmark Topic Watch Topic
  • New Topic

Putting objects derived from the same base to an ArrayList  RSS feed

 
Brian Ata
Greenhorn
Posts: 27
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi guys,

I have been experimenting with the Collections API, and came across a problem which seemed odd to me. The scenario is as follows:

Suppose we have abstract class AbstractClassA and then classes that extends this abstract class .. ClassB and ClassC ..
Assume that we want to store all extended classB and ClassC in the same ArrayList, how can we do that ?

Thanks,
 
dennis deems
Ranch Hand
Posts: 808
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Make the generic type of the collection AbstractClassA, then you can add any descendant of this class due to the Liskov substitution principle. When you get an element from the list, you will have a reference of type AbstractClassA, so if you need distinctly ClassB or ClassC behavior, you will have to cast to the desired type first.
 
Brian Ata
Greenhorn
Posts: 27
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Now I tried and naturally it works.

I was thinking the same thing you suggested but it didn't work when I tried since in my try out example I used a SortedSet as base/super class with a TreeSet for sorting objects in the Set. But after your post when I examined what I did, it turned out I implemented the Comparable interface in child classes instead of the abstract class, so again naturally the compiler got confused while trying to compare apples with oranges (ClassA with ClassB).

Now I carried the Comparable to Abstract class and overrided them in concerete classes and it works.

Thank you for your time Dennis!
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!