Contributed by Chris Rathman
Note: This version uses an object merge technique as described here. Currently Suneido only supports base classes which are defined globally in a library. The merge technique used has the disadvantage of not supporting delegation via the super() method.
shape = class { // constructor for shape class - not currently used New(x, y) { .MoveTo(x, y) } // accessors for x and y SetX(x) { .x = x } SetY(y) { .y = y } GetX() { return .x } GetY() { return .y } // move the x & y position of the object MoveTo(x, y) { .SetX(x); .SetY(y) } RMoveTo(dx, dy) { .MoveTo(.x + dx, .y + dy) } } stage_rectangle = class { New(x, y, width, height) { .MoveTo(x, y); .SetWidth(width); .SetHeight(height); } // accessors for width and height GetWidth() { return .width } GetHeight() { return .height } SetWidth(width) { .width = width } SetHeight(height) { .height = height } // draw the rectangle Draw() { Print("Draw a Rectangle at:(" $ .GetX() $ "," $ .GetY() $ "), width " $ .GetWidth() $ ", height " $ .GetHeight()) } } rectangle = Class(Object().Merge(shape).Merge(stage_rectangle)) stage_circle = class { // constructor for circle class New(x, y, radius) { .MoveTo(x, y); .SetRadius(radius); } // accessors for radius GetRadius() { return .radius } SetRadius(radius) { .radius = radius } // draw the circle Draw() { Print("Draw a Circle at:(" $ .GetX() $ "," $ .GetY() $ "), radius " $ .GetRadius()) } } circle = Class(Object().Merge(shape).Merge(stage_circle)) // set up some shape instances scribble = new Object(); scribble[0] = new rectangle(10, 20, 5, 6) scribble[1] = new circle(15, 25, 8) // iterate through the array and handle shapes polymorphically foreach (value x in scribble) { x.Draw() x.RMoveTo(100, 100) x.Draw() } // access a rectangle specific function arect = new rectangle(10, 20, 5, 6) arect.SetWidth(30) arect.Draw() |
Draw a Rectangle at:(10,20), width 5, height 6 Draw a Rectangle at:(110,120), width 5, height 6 Draw a Circle at:(15,25), radius 8 Draw a Circle at:(115,125), radius 8 Draw a Rectangle at:(10,20), width 30, height 6 "" |