module: shape
synopsis: OO - Shape, Circle, Rectangle
author: Michael Neumann
copyright: Copyright (c) 2002, Michael Neumann
// note:
// last two words after "end" are optional
// all type specifiers after "::" are optional
define class <color> (<object>)
slot red :: <number>,
init-value: 0,
init-keyword: red:;
slot green :: <number>,
init-value: 0,
init-keyword: green:;
slot blue :: <number>,
init-value: 0,
init-keyword: blue:;
end class <color>;
define class <shape> (<object>)
slot x :: <number>,
required-init-keyword: x:;
slot y :: <number>,
required-init-keyword: y:;
slot color :: <color>,
required-init-keyword: color:;
end class <shape>;
define class <circle> (<shape>)
slot radius :: <number>,
required-init-keyword: radius:;
end class <circle>;
define class <rectangle> (<shape>)
slot width :: <number>,
required-init-keyword: width:;
slot height :: <number>,
required-init-keyword: height:;
end class <rectangle>;
/* Define the methods */
define method move(shape :: <shape>, xo :: <number>, yo :: <number>)
shape.x := shape.x + xo;
shape.y := shape.y + yo;
end method move;
define method draw(shape :: <shape>)
// do something here
end method draw;
define method get-area(circle :: <circle>)
=> (area :: <number>)
3.1415 * circle.radius;
end method get-area;
define method get-area(rectangle :: <rectangle>)
=> (area :: <number>)
rectangle.width * rectangle.height;
end method get-area;
/* Test the classes */
define constant $black :: <color> =
make(<color>);
define constant $white :: <color> =
make(<color>, red: 255, green: 255, blue: 255);
define variable circle :: <circle> =
make(<circle>, x: 100, y: 100, radius: 50, color: $black);
define variable rect :: <rectangle> =
make(<rectangle>, x: 20, y: 20, width: 5, height: 5, color: $white);
move(circle, 10, 10);
circle.x := 50;
circle.radius := 5;
format-out("%=\n", get-area(circle)); // => 15
format-out("%=\n", get-area(rect)); // => 25
format-out("%=\n", rect.width); // => 5
width-setter(10, rect); // another way to set a slot
format-out("%=\n", width(rect)); // => 10
draw(circle);
draw(rect);