简体   繁体   中英

Polymorphism, Overloading and Overriding in Java with ArrayList

First of all, I'm sorry for possibly having an incorrect title, I might be thinking of something else but here goes. I have a simple program that is drawing out stars and circles in Java using the Processing applet. I have an ArrayList of type Shape.

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

I then add various stars and circles through a constructor which uses overloading to determine whether its a star or a circle.

For the star:

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

For the circle:

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

Once that is done, the task is to loop round the ArrayList to draw and render the shapes. The star and circle class both have their own draw methods to draw the shapes.

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

The problem I'm having, is that it is failing to override the empty draw() inside the Shape class when I want it to 'fall back' into the Star or Circle class and execute that specific draw() depending on whether the object is a star or circle at that point in the ArrayList.

Thanks!

Define a Shape interface

public interface Shape {

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

Implement a Circle

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");
    }
}

Implement a Star

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");
    }       

}

Add them to your list

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();
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM