Example #1
0
 @Override
 public int compareTo(Object obj) {
   if (obj instanceof Shape) {
     Shape shape = (Shape) obj;
     if (this.area() > shape.area()) return 1;
     else if (this.area() == shape.area()) return 0;
     else return -1;
   } else {
     return 9999999;
   }
 }
Example #2
0
 public double totalArea() {
   double tot = 0;
   for (Shape s : shape) {
     tot += s.area();
   }
   return tot;
 }
  @Test
  public void twentyFor4x5RectangleFromSquare() throws Exception {
    final Rectangle rectangle = new Rectangle();
    rectangle.setWidth(5);
    rectangle.setHeight(4);

    final Square square = new Square();
    square.setSideLength(3);

    List<Shape> shapes =
        new ArrayList<Shape>() {
          {
            add(rectangle);
            add(square);
          }
        };

    List<Integer> areas = new ArrayList<Integer>();
    for (Shape shape : shapes) {
      areas.add(shape.area());
    }

    assertEquals(20, areas.get(0).intValue());
    assertEquals(9, areas.get(1).intValue());
  }
Example #4
0
  public static void main(String args[]) {
    // declare an array of shapes, which will accept points or circles
    Shape shapes[] = new Shape[3];

    // adding one point and one circle
    shapes[0] = new Point(5, 1);
    shapes[1] = new Circle(2.5, 10, 5);
    shapes[2] = new Cylinder(3.6, 4.2);
    // Use the array reference object to display the correct information via polymorphism
    // this block only uses methods defined for all shapes, so
    // it will work for any shape that happens to be in the array
    for (Shape s : shapes) {
      System.out.println(s.getName() + ": " + s.toString() + "\nArea is " + s.area());
    }
  }