is there any diffrence between statement (3) and (4)? Is the declaration of (3) better (due to polomorphism) ? do I gain anything by using (3) instead of (4)? or did I just miss something really basic?
Joined: Oct 13, 2005
Welcome to JavaRanch
You find (3) has an advantage when you haveandThen you can easily change "new B()" to "new C()" or "new D()" and retain all your functionality.
Joined: Oct 01, 2009
Thanks for the reply.
Joined: Oct 22, 2009
Shay Levy wrote:Is the declaration of (3) better (due to polomorphism) ?
There's a design criterion saying: Use the highest abstraction level (upwards in the inheritance tree) that meets your needs.
Writing code using A variables will definately make your code more flexible and general because it will work with any subtype of A like B (and C and D and ....).
On the other hand the subtypes B and C and D may not be equally efficient when objects of these types are plugged into an algorithm written using A variables. Say B is excellent but C and D are disasters. In that case the A abstraction is too high and you should write your code using B variables instead.