A question about clone object in Java

B

Bruce Sam

/* *************************************************** */
class Point { // A messenger
public int x, y, z; // Since it's just a carrier
public Point(int x, int y, int z) {
this.x = x;
this.y = y;
this.z = z;
}
public Point(Point p) { // Copy-constructor
this.x = p.x;
this.y = p.y;
this.z = p.z;
}
public String toString() {
return "x: " + x + " y: " + y + " z: " + z;
}
}

class Space {
public static Point translate(Point p) {
// p = new Point(p); //Notice!
p.x = p.x + 1;
p.y = p.y + 1;
p.z = p.z + 1;
return p;
}
}

public class MessengerDemo {
public void test() {
Point p1 = new Point(1, 2, 3);
Point p2 = Space.translate(p1);
String result = "p1: " + p1 + " p2: " + p2;
System.out.println(result);
}
public static void main(String[] args) {
MessengerDemo demo = new MessengerDemo();
demo.test();
}
}
/* *************************************************** */
The above is my simply test program.No matter I remove the line
"p = new Point(p);",the output result is the same:
".p1: x: 1 y: 2 z: 3 p2: x: 2 y: 3 z: 4",But in my understanding,if i
remove the line "p = new Point(p)",the output result should be ".p1: x:
2 y: 3 z: 4 p2: x: 2 y: 3 z: 4".Is it right?
 
R

Ryan Stewart

[...]
The above is my simply test program.No matter I remove the line
"p = new Point(p);",the output result is the same:
".p1: x: 1 y: 2 z: 3 p2: x: 2 y: 3 z: 4",But in my understanding,if i
remove the line "p = new Point(p)",the output result should be ".p1: x:
2 y: 3 z: 4 p2: x: 2 y: 3 z: 4".Is it right?
It works as expected for me. With "p = new Point(p);", p1 remains 1, 2, 3.
Without it, p1 becomes 2, 3, 4. Are you sure you're compiling and running it
correctly?
 
B

Bruce Sam

Hello Stewart,
I have compiled and runned it.If I remove the line "p = new
Point(p);",p1 is also 1,2,3;But I thinked it should be 2,3,4.
 
R

Ryan Stewart

Bruce Sam said:
Hello Stewart,
I have compiled and runned it.If I remove the line "p = new
Point(p);",p1 is also 1,2,3;But I thinked it should be 2,3,4.
And it is. Did you compile it after you removed that line?
 
B

Bruce Sam

Hello Stewart,
Exactly,I have compiled it in these two situation.Following you
said,I thinked it may be a very strange problem.
 
A

Andrew Thompson

Hello Stewart,

As an aside. 'Stewart's first name*, is actually Ryan.

BTW - is your first name Bruce, or is it Sam?

* People usually refer to each other by first name on this group.
Unless they are arguing, ..then all bets are off. [ ;-) ]
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,774
Messages
2,569,598
Members
45,149
Latest member
Vinay Kumar Nevatia0
Top