Java方法易错点(一)

代码:

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的值。

示例图:(方法接收了point类型的对象,这个时候point还是指向main方法中的new Point,后来change方法自己new了一个point对象,就把point引用指向从main方法中的new Point对象改为change方法的new Point()对象)

image.png

你可能感兴趣的:(Java方法易错点(一))