混淆是通过引用的java调用和按值的概念调用

时间:2014-03-19 11:12:08

标签: java

是基于Call by reference或者按值调用的Java工作让我感到困惑吗?

class Point  {

    int x, y;

    public Point(int x, int y) {
        this.x = x;
        this.y = y;
    }
}

public class demo {

    public static void tricky(Point arg1, Point arg2)   {
        Point temp = arg1;
        arg1 = arg2;
        arg2 = temp;
    }

    public static void tricky(Point arg1, Point arg2)  {
        arg1.x = 100;
        arg1.y = 100;
    }

    public static void main(String [] args)  {

        Point pnt1 = new Point(0,0);
        Point pnt2 = new Point(0,0);
        System.out.println("X: " + pnt1.x + " Y: " +pnt1.y);
        System.out.println("X: " + pnt2.x + " Y: " +pnt2.y);
        tricky(pnt1,pnt2);
        System.out.println("X: " + pnt1.x + " Y:" + pnt1.y);
        System.out.println("X: " + pnt2.x + " Y: " +pnt2.y);
        tricky1(pnt1,pnt2);
        System.out.println("X: " + pnt1.x + " Y:" + pnt1.y);
        System.out.println("X: " + pnt2.x + " Y: " +pnt2.y);
    }
}  

在第一种方法(棘手)执行后我感到困惑我得到了预期的结果,但不是在第二种方法(棘手)之后。

1 个答案:

答案 0 :(得分:0)

通过价值。这段代码:

public static void main(final String... args)
{
    String s = "foo";
    tryAndModify(s);
    System.out.println(s);
}

private static void tryAndModify(String s)
{
    s = "bar";
}

将打印foo

s是对String对象的引用,当然。但这是一个值作为方法调用参数。例如,像C ++一样,“通过引用传递”是一个独立的概念。