/*********************************************** * CS2510 Fall 2011 * Lecture #3 * Data and Methods (instance functions) ***********************************************/ // 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()); } } /* Posn template... the laundry list ** Fields of "this" class ... this.x ... -- int ... this.y ... -- int ** We also add methods that we implement (and test) ... this.moveUp(int dy) ... -- Posn ... this.distTo0() ... -- double ... this.moveUpBy(Posn p) -- Posn ** If we have methods that we can call on fields of "this" then they go HERE ... */ /* We still do purpose statements, but the contract and * header are now part of the (Java-like) language */ class Posn { int x; int y; Posn(int xcoord, int ycoord) { this.x = xcoord; this.y = ycoord; } // 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() { } }