2017-04-17 58 views
0

首先,我很抱歉可能有一个不正确的标题,我可能会想到其他的东西,但在这里。我有一个简单的程序,它使用Processing applet在Java中绘制星星和圆圈。我有一个类型为Shape的ArrayList。使用ArrayList进行Java中的多态,重载和重载

ArrayList<Shape> shapeList= new ArrayList<Shape>(); 

我再通过它采用重载来确定其星形或圆形构造函数添加各种明星及各界。

对于明星:

shapeList.add(new Shape(x, y, size, colour, numPoints, pApp)); 

对于圈:

shapeList.add(new Shape(x, y, size, colour, pApp)); 

一旦做到这一点,任务是循环轮ArrayList的绘制和呈现的形状。星形和圆形类都有自己的绘制方法来绘制形状。

for (Shape shape: shapeList) 
    { 
     shape.update(); 
     shape.draw(); 
    } 

我遇到的问题是,它未能改写平局空()Shape类的内部时,我希望它“回落”到明星或Circle类和执行具体平局()取决于该对象是否是ArrayList中该点处的星形或圆形。

谢谢!

+1

但是你没有实例化'Star'或'Circle',你正在实例化'Shape's ...你需要使用适当类的构造函数。 – Zircon

+0

对于明星,我建议添加一个Polygon/Polygon2D。对于Circle,我建议添加一个Ellipse2D。 – ControlAltDel

+0

@Zircon是的,这是一个错误,谢谢! – badprogramming99

回答

0

定义Shape接口

public interface Shape { 

    // the methods circle and star need to implement 
    void update(); 
    void draw(); 
} 

实现一个圈

public class Circle implements Shape { 


    public Circle(int x, int y, int size, Color colour, App pApp){ 
     // your code 
    } 

    @Override 
    public void draw() { 
     System.out.println("Drawing Circle"); 
    } 

    @Override 
    public void update() { 
     System.out.println("Updating Circle"); 
    } 
} 

实现一个星

public class Star implements Shape { 


    public Circle(int x, int y, int size, int numPoints, Color colour, App pApp){ 
     // your code 
    } 

    @Override 
    public void draw() { 
     System.out.println("Drawing Star"); 
    } 
    @Override 
    public void update() { 
     System.out.println("Updating Star"); 
    }  

} 

它们添加到您的列表

shapeList.add(new Star(x, y, size, colour, numPoints, pApp)); 
shapeList.add(new Circle(x, y, size, colour, pApp)); 
shapeList.add(new Star(x, y, size, colour, numPoints, pApp)); 
shapeList.add(new Circle(x, y, size, colour, pApp)); 

for (Shape shape: shapeList) 
{ 
    shape.update(); 
    shape.draw(); 
}