PointCoordinates

• 05-08-2014, 10:25 AM
toiletpaper
PointCoordinates
What are the x- and y-coordinates of the Points referred to as p1, p2, and p3 after the following code executes? Give your answer as an x-y pair such as (0, 0). (Recall that Points and other objects use reference semantics.

Code:

```Point p1 = new Point(); p1.x = 17; p1.y = 9; Point p2 = new Point(); p2.x = 4; p2.y = -1; Point p3 = p2; p1.translate(3, 1); p2.x = 50; p3.translate(-4, 5);```

P1:
P2:
P3:

My guesses were: P1:(20,10) //Correct
P2:(50,-1) //Incorrect
P3:(0,4) //Incorrect
• 05-08-2014, 10:45 AM
SurfMan
Re: PointCoordinates
The tricky part is at line 7: p3 points (no pun intended) to the same Point in memory as p2. The change you make to p3 will be performed on the same instance as p2. So, p2 and p3 always return the same values since they point to the same object.
• 05-08-2014, 01:02 PM
toiletpaper
Re: PointCoordinates
But what would the values turn out to be ?

p2.x = 50; that should change the value of p2.x=4 into p2.x=50 i presume, but its still a wrong answer.
• 05-08-2014, 01:46 PM
SurfMan
Re: PointCoordinates
Quote:

Originally Posted by toiletpaper
But what would the values turn out to be ?

p2.x = 50; that should change the value of p2.x=4 into p2.x=50 i presume, but its still a wrong answer.

Yeah, true, but after that, p3 is translated, so the values for p2 change as well, since those variables point to the same object.
• 05-08-2014, 03:14 PM
Tolls
Re: PointCoordinates
p1, p2 and p3 are references to Point objects.
They are not the objects themselves.

p1 refers to a Point that was created on this line:
Code:

`Point p1 = new Point();`
p2 refers to a Point that was created on this line:
Code:

`Point p2 = new Point();`
These are two different objects, so anything done via p1 will not affect the object referred to by p2, and vice versa.

p3 is declared as referring to p2, on this line:
Code:

`Point p3 = p2;`
This means that anything done via the p2 reference or the p3 reference will affect the same underlying object. There is only the one object.