class ReferencesTest {
public static void main(String[] arguments) {
Point pt1, pt2;
pt1 = new Point(100, 100);
pt2 = pt1; pt1.x = 200;
pt1.y = 200;
System.out.println("Point1: " + pt1.x + ", " + pt1.y);
System.out.println("Point2: " + pt2.x + ", " + pt2.y);
}
}
答案:Point1: 200, 200
Point2: 200, 200
为什么不是Point1: 200, 200
Point2: 100,100呢,
Point pt1, pt2;
pt1 = new Point(100, 100);
pt2 = pt1; pt1.x = 200;
pt1.y = 200;
System.out.println("Point1: " + pt1.x + ", " + pt1.y);
System.out.println("Point2: " + pt2.x + ", " + pt2.y);
等于Point pt1, pt2;
pt1 = new Point(100, 100);
pt1.x = 200;
pt1.y = 200;
pt2 = pt1;
System.out.println("Point1: " + pt1.x + ", " + pt1.y);
System.out.println("Point2: " + pt2.x + ", " + pt2.y);么?????
public static void main(String[] arguments) {
Point pt1, pt2;
pt1 = new Point(100, 100);
pt2 = pt1; pt1.x = 200;
pt1.y = 200;
System.out.println("Point1: " + pt1.x + ", " + pt1.y);
System.out.println("Point2: " + pt2.x + ", " + pt2.y);
}
}
答案:Point1: 200, 200
Point2: 200, 200
为什么不是Point1: 200, 200
Point2: 100,100呢,
Point pt1, pt2;
pt1 = new Point(100, 100);
pt2 = pt1; pt1.x = 200;
pt1.y = 200;
System.out.println("Point1: " + pt1.x + ", " + pt1.y);
System.out.println("Point2: " + pt2.x + ", " + pt2.y);
等于Point pt1, pt2;
pt1 = new Point(100, 100);
pt1.x = 200;
pt1.y = 200;
pt2 = pt1;
System.out.println("Point1: " + pt1.x + ", " + pt1.y);
System.out.println("Point2: " + pt2.x + ", " + pt2.y);么?????
之后pt2,pt1指向了同一个内存单元
pt2=new Point(1,1);
Point类在定义变量的时候用了static
可能是:
private static int x;
privtat static int y;
pt1 = new Point(100, 100);//这时候Point1: 100,100
pt2 = pt1; //pt2被赋予pt1的实例(pt1和pt2引用相同的实例),
//point2:100,100 pt1.x = 200;
pt1.y = 200; //point1:200,200,由于pt1和pt2引用相同的实例
//point2:200,200
Point类在定义变量的时候用了static
可能是:
private static int x;
privtat static int y;
没有static也是这样
class Point{
int x
}
public class ReferencesTest{
public static void main(String[] args){
Point p1=new Point();
Point p2=new Point();
p1.x=100;
p2.x=200;
System.out.println("p1.x="+p1.x+"p2.x="+p2.x);
p1=p2;//当我们进行对象相互赋值的时候,实际上是把它们的“引用”复制了
System.out.println("p1.x="+p1.x+"p2.x="+p2.x);
}
}
我举的这个前人的例子虽说和楼主的不太一样,但是原理是一样的,楼主可以试着执行,看一下结果的区别,就会很容易明白了。(小生比较懒,就不RESULT了)最后说的是,如果想避免这种“别名”问题怎么办,可以把这两个对象独立,把上面p1=p2;换成p1.x=p2.x;试试看
当运行到pt2=pt1这条语句时,就都指向了pt1 = new Point(100, 100);的这个Point对象.pt2原来所new出来的对象就无法访问到了,所以你以后操作这两个变量其实是在操作同一个内存空间,所打印出来的东西也就是一样的了...