Thinking in Java Fourth Edition Bruce Eckel Chapter 7 Exercise 3

Exercise 3: Add a new method in the base class of Shapes.java that prints a message, but don’t override it in the derived classes. Explain what happens. Now override it in one of the derived classes but not the others, and see what happens. Finally, override it in all the derived classes.

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();
        }
    }
}
package polymorphism.shape;
public class Shape
{
    public void draw()
    {
    }
    public void erase()
    {
    }
    public void amend()
    {
        System.out.println("Shape.amend()");
    }
}
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()");
    }
    @Override public void amend()
    {
        System.out.println("Circle.amend()");
    }
}
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()");
    }
    @Override public void amend()
    {
        System.out.println("Square.amend()");
    }
}
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()");
    }
    @Override public void amend()
    {
        System.out.println("Triangle.amend()");
    }
}
import polymorphism.shape.*;

public class Shapes3
{
    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();
            shp.amend();
        }  
    }
}

Output:

2 Replies to “Thinking in Java Fourth Edition Bruce Eckel Chapter 7 Exercise 3”

Leave a Reply

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