TWiki . Doc . ShapesIntermediateExample

/* Please try the BeginnerExamples before the IntermediateExamples
To compile:
   nicec --sourcepath=.. -a shapes.jar shapes
To run:
   java -jar shapes.jar
*/

// Let's assume we want to extend and re-use the classes defined in the 
// ShapesBeginnerExample. Let's also assume that we want to define an 
// interface so doSomething isn't restricted to Shape subclasses.

<IShape S> void doSomething( S shape ){
   shape.draw;
   shape.moveByI(100, 100);
   shape.draw;
}


// Our abstract interface should include moveBy and draw
// currently we have to use a different name than moveBy
// (in future we'll be able to qualify moveBy with a package name)

abstract interface IShape {
   void moveByI(int dx, int dy);
   void draw();
}


// The Shape class is already written
// Now we need it to implement IShape

class shapes.Shape implements IShape;


// The Nice compiler will detect that the Shape classes don't
// implement draw methods - so let's implement them

draw(Rectangle this){
   println("Drawing a Rectangle at (" + x + ", " + y +"), 
      width " + width + ", height " + height);
}

draw(Circle this){
   println ("Drawing a Circle at (" + x + "," + y + "),
      radius " + radius);
}


// The Shape classes have a moveBy method they need a 
// moveByI method for the IShape interface

moveByI(Shape this, dx, dy){
   this.moveBy(dx, dy);
}


// We've extended the Shape classes Rectangle and Circle
// for the IShape interface let's use them 

void main(String[] args){     
   let Shape[] scribble = [ 
      new Rectangle(x: 10, y: 20, width: 5, height: 6),
      new Circle(x: 15, y: 25, radius: 8)
      ];

   for (each : scibble) doSomething(each);

   let rect = new Rectangle(x: 0, y: 0, width: 15, height: 15);
   rect.setWidth(30);
   rect.draw;
}


/* Notes - language
   Compare with other OO languages
http://onestepback.org/articles/poly/
http://www.angelfire.com/tx4/cus/shapes/

   c:\projects\shapes> nicec --sourcepath=.. -a shapes.jar shapes
nice.lang: parsing
shapes: parsing
shapes: typechecking
shapes: generating code
shapes: linking
shapes: writing in archive
nice.lang: writing in archive

   c:\projects\shapes> java -jar shapes.jar
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
*/
-- IsaacGouy - 24 Dec 2003

----- Revision r1.4 - 24 Dec 2003 - 21:28 GMT - IsaacGouy
Copyright © 1999-2003 by the contributing authors. All material on this collaboration platform is the property of the contributing authors.
Ideas, requests, problems regarding TWiki? Send feedback.