代码:
public class Point {
int x ;
int y ;
}
public class TestPoint {
public void change(Point point){
point.x = 3;
point.y = 4;
}
public static void main(String[] args) {
TestPoint testPoint = new TestPoint();
Point point = new Point();
testPoint.change(point);
System.out.println(point.x);
System.out.println(point.y);
}
}
----------------------------------------------------------------------------
结果:
x的值为:3
y的值为:4
修改下代码:
public class Point {
int x ;
int y ;
}
public class TestPoint {
public void change(Point point){
point = new Point();
point.x = 3;
point.y = 4;
}
public static void main(String[] args) {
TestPoint testPoint = new TestPoint();
Point point = new Point();
testPoint.change(point);
System.out.println(point.x);
System.out.println(point.y);
}
}
----------------------------------------------------------------------------
结果:
x的值为:0
y的值为:0
总结:
因为方法中新增的“point = new Point();”代码,新增了一个Point的对象。所以是给新的对象的x,y分配赋值。而main方法中的print打印的还是之前的Point对象,直接调用Point类中x,y的值。
网友评论