多态形状类绘制最近创建的任何形状?

时间:2016-11-08 04:13:39

标签: java swing inheritance polymorphism shape

我有继承自Shape的Triangle和Circle类,以及一个类似于绘制圆形和三角形的类:

public class Application extends JPanel{

@Override
protected void paintComponent(Graphics g){

    super.paintComponent(g);
    Shape[] shapes = new Shape[4];
    Circle circle1 = new Circle(100,100,80);
    Triangle tri1 = new Triangle(20,40,40);
    Circle circle2 = new Circle(300,300,100);
    Triangle tri2 = new Triangle(30,30,30);

    shapes[0] = circle1;
    shapes[1] = tri1;
    shapes[2] = circle2;
    shapes[3] = tri2;

    for(Shape shape : shapes){
        shape = (Shape) shape;
        shape.draw(g, this);
        }

    }
}

代码绘制圆圈没有错误,但绘制的三角形始终是第二个(tri2)。我一直在玩,并意识到绘制的三角形总是最后定义的三角形。我想知道为什么会出现这种情况?

1 个答案:

答案 0 :(得分:0)

我为每个类标记了值x和y,标记了从哪里开始绘制每个形状,这些变量是为超类和子类静态定义的。这导致Triangle的x和y分量用最新的对象定义。