No additional data needed, as the coordinates of the origin are known. We will compute the distance in city blocks, rather than finding the length of a direct line between the origin and the Posn that invokes the method.
// compute the distance of this Posn to the origin
int distTo0() { ... }
Posn p1 = new Posn(10, 20); Posn p2 = new Posn(20, 20); // p1.distTo0() -- expected: 30 // p2.distTo0() -- expected: 40
The first varsion of the template is the same for all methods in a class.
// ** DRAFT TEMPLATE ** Edit as needed.
??? mmm() {
... this.x ...
... this.y ...
}
// compute the distance of this Posn to the origin
int distTo0() {
return this.x + this.y;
}
We use the Test Tool, or write the tests in the Interactions Box:
/* Interactions: p1.distTo0() == 30 p2.distTo0() == 40 */
The method is invoked by one Posn. We need another Posn as an argument for this method. No additional information is needed.
// determine whether this Posn is closer to the origin
// than the given Posn
boolean closer(Posn that){...}
p1.closer(p2) -- expected: true p2.closer(p1) -- expected: false
boolean closer(Posn that) {
... this.x ... ... that.x ...
... this.y ... ... that.y ...
... this.distTo0() ... ... that.distTo0() ...
}
// compute the distance from this Posn to the given Posn
boolean closer(Posn that){
return this.distTo0() < that.distTo0();
}
p1.closer(p2) == true p2.closer(p1) == false