/*********************************** * CS2510 Spring 2011 * Lecture #4.1 * Methods, Unions, and Interfaces ***********************************/ import tester.*; // Represents a Location (X/Y) class Loc{ int x; int y; Loc(int x, int y){ this.x = x; this.y = y; } /* Fields of "this" ... this.x ... -- int ... this.y ... -- int Methods of "this" ... this.distTo0() -- double ... this.moveLeft() -- Loc ... this.move(int, int) -- Loc ... this.distTo(Loc) -- Loc Methods of fields */ // Calculate the distance to (0,0) from "this" Loc double distTo0(){ return Math.sqrt((this.x * this.x) + (this.y * this.y)); } // Move this Loc to the Left 5 units Loc moveLeft(){ return new Loc((this.x - 5), this.y); } // Creates a new location right/down of this one Loc move(int dx, int dy){ return new Loc(this.x + dx, this.y + dy); } // Calculate the distance between this Loc and the // given location double distTo(Loc that){ return (that.move(-this.x, -this.y)).distTo0(); } } //Examples and Tests for our Classes and Methods class LocExamples{ LocExamples(){} Loc here = new Loc(4, 3); Loc there = new Loc(4, 4); boolean testDistTo0(Tester t){ return t.checkExpect(this.here.distTo0(), 5.0); } boolean testMoveLeft(Tester t){ return t.checkExpect(this.here.moveLeft(), new Loc(-1, 3)); } boolean testMove(Tester tee){ return tee.checkExpect(this.here.move(1, 3), new Loc(5, 6)); } boolean testDistTo(Tester t){ return t.checkExpect(this.there.distTo(this.here), 1.0); } } //Represents a Shape interface IShape{ // Compute distance to (0,0) for this IShape double distTo0(); } // Represents a Circle Shape class Circle implements IShape{ Loc c; int r; Circle(Loc c, int r){ this.c = c; this.r = r; } /* Template Fields ... this.c ... -- Loc ... this.r ... -- int Methods ... this.distTo0() ... -- double Methods of Fields ... this.c.distTo0() ... -- double ... this.c.moveLeft() ... -- Loc ... this.c.move(int, int) ... -- Loc ... this.c.distTo(Loc) ... -- double */ // Computes Distance to (0,0) for this Circle double distTo0(){ return this.c.distTo0() - this.r; } } // Represents a Rectangle Shape class Rect implements IShape{ Loc tl; int w; int h; Rect(Loc tl, int w, int h){ this.tl = tl; this.w = w; this.h = h; } // Distance to (0,0) for this Rect double distTo0(){ return this.tl.distTo0(); } } //Examples and Tests for our Classes and Methods class ShapeExamples{ ShapeExamples(){} IShape rect = new Rect(new Loc(4, 3), 4, 5); IShape circ = new Circle(new Loc(12, 9), 3); boolean testShapes(Tester t){ return (t.checkExpect(this.circ.distTo0(), 12.0) && t.checkExpect(this.rect.distTo0(), 5.0)); } }