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?
Thanks
Campbell Ritchie
Sheriff
Joined: Oct 13, 2005
Posts: 32712
4
posted
0
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.
Shay Levy
Greenhorn
Joined: Oct 01, 2009
Posts: 7
posted
0
Thanks for the reply.
Embla Tingeling
Ranch Hand
Joined: Oct 22, 2009
Posts: 237
posted
0
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.