Java Reference
In-Depth Information
15 setLocation(x, y);
16 }
17
18 // returns the distance between this Point and (0, 0)
19
public double
distanceFromOrigin() {
20
return
Math.sqrt(x * x + y * y);
21 }
22
23 // returns the x-coordinate of this point
24
public int
getX() {
25
return
x;
26 }
27
28 // returns the y-coordinate of this point
29
public int
getY() {
30
return
y;
31 }
32
33 // sets this point's (x, y) location to the given values
34
public void
setLocation(
int
x,
int
y) {
35
this
.x = x;
36
this
.y = y;
37 }
38
39 // returns a String representation of this point
40
public String
toString() {
41
return
"(" + x + ", " + y + ")";
42 }
43
44 // shifts this point's location by the given amount
45
public void
translate(
int
dx,
int
dy) {
46 setLocation(x + dx, y + dy);
47 }
48 }
Here's the corresponding final version of our client program, which now uses the
Point
constructors and methods appropriately:
1 // A program that deals with points.
2 // Fourth version, to accompany encapsulated Point class.
3
4
public class
PointMain {
5
public static void
main(String[] args) {
6 // create two Point objects
7 Point p1 =
new
Point(7, 2);
Search WWH ::
Custom Search