why java polymorphism not work in my example

This is one of the problems of using visible fields – you end up using them…

You’ve got a color field in both Rect and CRect. Fields are not polymorphic, so when you use cr2.color, that uses the field declared in Rect, which is always set to "transparent".

Your CRect class should not have its own color field – it should supply the colour to the superclass constructor. It makes no sense for a single rectangle to have two different color fields – it could have borderColor and fillColor, of course – but just color is too ambiguous…

Leave a Comment