-3

Editing my question because I realized better what I want:

Say we have List<A> with bunch of instances of classes extending A each with its own unique properties.

Like in this example:

  1. class A has field int x, getter and setter.
  2. class B extends A, and also has field int y with its getter and setter.
  3. class C extends A, and also has field int z with its getter and setter.

I don't want to use downcasting and instanceof when iterating the list.

I read this post which was interesting: https://softwareengineering.stackexchange.com/questions/245263/how-to-avoid-downcasting

What is the right approach?

Thanks

belostoky
  • 934
  • 2
  • 11
  • 22

2 Answers2

0

In most cases, you should be doing B b = new B() instead of A b = new B(). If you must use a field of type A, then downcasting is your best bet. Keep in mind, though, that it shouldn't happen very often.

Sam
  • 2,350
  • 1
  • 11
  • 22
  • Thanks for your answer, I changed my question a bit. – belostoky Apr 01 '18 at 20:27
  • This answer is wrong for the general case. The main rule is to code to the interface, to the abstraction, not to the concrete. Avoid coding to the concrete unless absolutely necessary. There are whole design patterns created to avoid doing this, such as the Visitor Pattern. – Hovercraft Full Of Eels Apr 01 '18 at 20:28
0

Yes, it does makes sense for a sub-class to have more fields than it's super.

If you find yourself having to downcast, then it likely means that you should instantiate the variable with the static class that you are down-casting to, in this case, do B b = new B() instead of A b = new B(). When you use A b = new B(), it means the context/function in which you want to use the variable expects an object of type A (i.e. expects to use functions that are declared in A), therefore if you are down-casting to B, you may need to review your design and ask yourself the data type that you want to work with in that context/function.

wes
  • 1
  • 2