why java polymorphism not work in my example

风流意气都作罢 提交于 2019-11-26 11:24:53

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...

You should include an explicit super() call in your subclasses' constructors:

public CRect(double w, double h ,String c) {
    super(w, h);
    width=w;
    height=h;
    color=c;
}

cr2.area() will call CRect.area() but cr2.color will use the field Rect.color. You should use the function style getArea() and have CRect.getColor() { return color; } as well as Rect.getColor() { return color; }

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!