Thinking in Java Fourth Edition Bruce Eckel Chapter 7 Exercise 2

Exercise 2: Add the @Override annotation to the shapes example.

package polymorphism.shape;
public class Shape
{
    public void draw()
    {
    }
    public void erase()
    {
    }
}
package polymorphism.shape;
public class Square extends Shape
{
    @Override public void draw()
    {
        System.out.println("Square.draw()");
    }
    @Override public void erase()
    {
        System.out.println("Square.erase()");
    }
}
package polymorphism.shape;
public class Triangle extends Shape
{
    @Override public void draw()
    {
        System.out.println("Triangle.draw()");
    }
    @Override public void erase()
    {
        System.out.println("Triangle.erase()");
    }
}
package polymorphism.shape;
public class Circle extends Shape
{
    @Override public void draw()
    {
        System.out.println("Circle.draw()");
    }
    @Override public void erase()
    {
        System.out.println("Circle.erase()");
    }
}
package polymorphism.shape;
import java.util.*;
public class RandomShapeGenerator
{
    private Random rand = new Random();
    public Shape next()
    {
        switch(rand.nextInt(3))
        {
            default:
            case 0: return new Circle();
            case 1: return new Square();
            case 2: return new Triangle();
        }
    }
}
import polymorphism.shape.*;

public class Shapes
{
    private static RandomShapeGenerator gen = new RandomShapeGenerator();
    public static void main(String[] args)
    {
        Shape[] s = new Shape[10];
        // fill up the array wth shapes:
        for(int i = 0; i < s.length; i++)
            s[i] = gen.next();
        // make polymorphic method calls:
        for(Shape shp : s)
            shp.draw();
    }
}

Output:

Leave a Reply

Your email address will not be published. Required fields are marked *