/*********************************************** * CS2510 Fall 2011 * Lecture #4.1 * Data and Methods (instance functions) ***********************************************/ import tester.*; // IShape represents a shape interface IShape { // shapeDistTo0 returns the distance from the shape to the origin double shapeDistTo0(); } // A Circle (as a type of IShape) class Circle implements IShape { int rad; Posn center; Circle(int rad, Posn center) { this.rad = rad; this.center = center; } // shapeDistTo0: The distance from the center of the circle to the origin public double shapeDistTo0() { return center.distTo0(); } } //A Rectangle (as a type of IShape) class Rect implements IShape { int h; int w; Posn center; Rect(int h, int w, Posn center) { this.h = h; this.w = w; this.center = center; } // shapeDistTo0: The distance from the center of the rectangle to the origin public double shapeDistTo0() { return center.distTo0(); } } class Overlay implements IShape{ IShape s1; IShape s2; Overlay(IShape s1, IShape s2) { this.s1 = s1; this.s2 = s2; } // shapeDistTo0: The distance from the closest sub-shape to the origin public double shapeDistTo0() { return Math.min(s1.shapeDistTo0(),s2.shapeDistTo0()); } } /* We still do purpose statements, but the contract and * header are now part of the (Java-like) language */ class Posn { int x; int y; /* * Fields of *this*: * ... this.x ... -- int * ... this.y ... -- int * * Methods of *this*: * ... this.moveUp(int) ... -- Posn * ... this.moveUpBy(Posn) ... -- Posn * ... this.distTo0() ... -- double */ Posn(int x, int y) { this.x = x; this.y = y; } // moveUp returns a new Posn shifted up by dy Posn moveUp(int dy) { return new Posn(this.x, this.y+dy); } // moveUpBy returns a new Posn shifted by p.x and p.y Posn moveUpBy(Posn p) { return new Posn(this.x + p.x, this.y + p.y); } // distTo0 returns the distance from this posn to 0 double distTo0() { return Math.sqrt(Math.pow(this.x,2) + Math.pow(this.y,2)); } } class Examples { //Examples of shapes Circle c = new Circle(5,new Posn(1,2)); Rect r = new Rect(2,3,new Posn(5,4)); Overlay o = new Overlay(c,r); Overlay o2 = new Overlay(o,c); // Examples of Posns and Posn methods Posn p1 = new Posn(1,2); Posn p2 = p1.moveUp(10); Posn p3 = p2.moveUpBy(p1.moveUp(5)); Double p1dist = p1.distTo0(); // Examples of Shape Methods Double cdist = c.shapeDistTo0(); Double o2dist = o2.shapeDistTo0(); Examples() { } boolean testMoveUp(Tester t) { return t.checkExpect(this.p1.moveUp(5).y,7) && t.checkExpect(this.p1.moveUp(0),p1); } boolean testDistTo0(Tester t) { return t.checkExpect(this.p1.distTo0(), Math.sqrt((1*1)+(2*2))); } }