Unicon

Contributed by Chris Rathman

Shape Class (shape.icn)

class Shape(x, y)
   # accessors for x & y coordinates
   method getX()
      return x
   end
   method getY()
      return y
   end
   method setX(newx)
      x := newx
   end
   method setY(newy)
      y := newy
   end

   # move the x & y coordinates
   method moveTo(newx, newy)
      setX(newx)
      setY(newy)
   end
   method rMoveTo(deltax, deltay)
      moveTo(x + deltax, y + deltay)
   end

   # abstract draw method
   method draw()
   end
end

Rectangle Class (rectangle.icn)

class Rectangle : Shape(x, y, width, height)
   # accessors for the width & height
   method getWidth()
      return width
   end
   method getHeight()
      return height
   end
   method setWidth(newwidth)
      width := newwidth
   end
   method setHeight(newheight)
      height := newheight
   end

   # draw the rectangle
   method draw()
      writes("Drawing a Rectangle at:(");
      writes(getX());
      writes(",");
      writes(getY());
      writes("), width ");
      writes(getWidth());
      writes(", height ");
      write(getHeight())
   end
end

Circle Class (circle.icn)

class Circle : Shape(x, y, radius)
   # accessors for the radius
   method getRadius()
      return radius
   end
   method setRadius(newradius)
      radius := newradius
   end

   # draw the circle
   method draw()
      writes("Drawing a Circle at:(");
      writes(getX());
      writes(",");
      writes(getY());
      writes("), radius ");
      write(getRadius())
   end
end

Try shapes function (polymorph.icn)

procedure main()
   # create a list containing various shape instances
   scribble := [Rectangle(10, 20, 5, 6), Circle(15, 25, 8)];

   # iterate through the list and handle shapes polymorphically
   every each := !scribble do {
      each.draw();
      each.rMoveTo(100, 100);
      each.draw();
   }

   # access a rectangle specific function
   rect := Rectangle(0, 0, 15, 15);
   rect.setWidth(30);
   rect.draw();
end

Compiling

unicon -c shape.icn
unicon -c rectangle.icn
unicon -c circle.icn
unicon polymorph.icn shape.u rectangle.u circle.u
polymorph.exe

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

Chris Rathman / Chris.Rathman@tx.rr.com