I need to keep B and C on the same list because I want to sort them based on their shared attributes which I can.
As long as the requirement is to keep the list sorted with mixed types B
, C
both extending A
an to call their non-inherited methods, you have no choice than using the List<A>
containing all types.
Although I also try to avoid downcasting when possible, it doesn't mean there are situations when it is neither useful nor necessary.
for (A item: sortedList) {
if (item instanceof B) {
Whatever fieldB = ((B) item).getFieldB(); // using non-inherited method of B
} else if (item instanceof C) {
Whatever fieldC = ((C) item).getFieldC(); // using non-inherited method of C
} else {
// either only A or anything different that extends A
}
}
As of Java 14 thanks to JEP 305: Pattern Matching for instanceof, such thing gets less verbose:
for (A item: sortedList) {
if (item instanceof B b) {
Whatever fieldB = b.getFieldB(); // using non-inherited method of B
} else if (item instanceof C c) {
Whatever fieldC = c.getFieldC(); // using non-inherited method of C
} else {
// either only A or anything different that extends A
}
}