Java Reference
In-Depth Information
1. A new Point object is created and allocated in memory.
2. The Point constructor is called on the newly created object, passing 7 and 2 as
the initialX and initialY parameter values.
3. A Point reference variable named p is created and set to refer to the newly cre-
ated object.
Here is the complete code for the third version of our Point class, which now
contains a constructor:
1 // A Point object represents a pair of (x, y) coordinates.
2 // Third version: state and behavior with constructor.
3
4 public class Point {
5 int x;
6 int y;
7
8 // constructs a new point with the given (x, y) location
9 public Point( int initialX, int initialY) {
10 x = initialX;
11 y = initialY;
12 }
13
14 // returns the distance between this point and (0, 0)
15 public double distanceFromOrigin() {
16 return Math.sqrt(x * x + y * y);
17 }
18
19 // returns a String representation of this Point
20 public String toString() {
21 return "(" + x + ", " + y + ")";
22 }
23
24 // shifts this point's location by the given amount
25 public void translate( int dx, int dy) {
26 x += dx;
27 y += dy;
28 }
29 }
Calling a constructor with parameters is similar to ordering a car from a factory:
“I'd like the yellow one with power windows and a CD player.” You might not need
to specify every detail about the car, such as the fact that it should have four wheels
and headlights, but you do specify some initial attributes that are important to you.
 
Search WWH ::




Custom Search