{ |one, step, back| }

The Shape Example in Eiffel

Contributed by Jim Weirich

Code for Eiffel

File: shape.e

deferred class SHAPE
feature
   draw is deferred end;
   moveto (newx : INTEGER; newy : INTEGER) is deferred end;
   rmoveto (dx : INTEGER; dy : INTEGER) is deferred end;
end -- class SHAPE

File: rectangle.e

class RECTANGLE 
inherit
   SHAPE

creation
   make_at

feature
   make_at (newx, newy, neww, newh : INTEGER) is
      do
	 x := newx
	 y := newy
	 width := neww
	 height := newh
      end

   draw is 
      do
	 io.put_string ("Drawing a Rectangle at (")
	 io.put_integer (x)
	 io.put_string (",")
	 io.put_integer (y)
	 io.put_string ("), width ")
	 io.put_integer (width)
	 io.put_string (", height ")
	 io.put_integer (height)
	 io.put_new_line
      end

   moveto (newx : INTEGER; newy : INTEGER) is 
      do
	 x := newx
	 y := newy
      end
   
   rmoveto (dx : INTEGER; dy : INTEGER) is 
      do
	 x := x + dx
	 y := y + dy
      end

   set_width (newwidth : INTEGER) is
      do
	 width := newwidth;
      end

   set_height (newheight : INTEGER) is
      do
	 height := newheight;
      end

feature {NONE}
   x : INTEGER
   y : INTEGER
   width : INTEGER
   height : INTEGER
end

File: circle.e

class CIRCLE 
inherit
   SHAPE

creation
   make_at

feature
   make_at (newx, newy, newradius : INTEGER) is
      do
	 x := newx
	 y := newy
	 radius:= newradius
      end

   draw is 
      do
	 io.put_string ("Drawing a Circle at (")
	 io.put_integer (x)
	 io.put_string (",")
	 io.put_integer (y)
	 io.put_string ("), radius ")
	 io.put_integer (radius)
	 io.put_new_line
      end

   moveto (newx : INTEGER; newy : INTEGER) is 
      do
	 x := newx
	 y := newy
      end
   
   rmoveto (dx : INTEGER; dy : INTEGER) is 
      do
	 x := x + dx
	 y := y + dy
      end

   set_radius (newradius : INTEGER) is
      do
	 radius := newradius;
      end

feature {NONE}
   x : INTEGER
   y : INTEGER
   radius: INTEGER
end

File: try_shape.e

class TRY_SHAPE
creation
   make

feature
   make is
      local
	 shapes : ARRAY[SHAPE];
	 r : RECTANGLE;
	 s : SHAPE;
	 i : INTEGER;
      do
	 !!shapes.make(0,1);

	 !RECTANGLE!s.make_at (10, 20, 5, 6);
	 shapes.put (s, 0);

	 !CIRCLE!s.make_at (15, 25, 8);
	 shapes.put(s, 1);

         from
	    i := 0;
	 until
	    i = 2
	 loop
	    do_something_with_shape (shapes.item(i));
	    i := i+1
	 end

	 !!r.make_at(0, 0, 15, 15)
	 r.set_width(30);
	 r.draw;
      end

   do_something_with_shape (s : SHAPE) is
      require
	 s /= void
      do
	 s.draw
	 s.rmoveto (100, 100)
	 s.draw
      end
end

Output

Drawing a Rectangle at (10,20), width 5, height 6
Drawing a Rectangle at (110,120), width 5, height 6
Drawing a Circle at (15,25), radius 8
Drawing a Circle at (115,125), radius 8
Drawing a Rectangle at (0,0), width 30, height 15