我想我理解它是传递给方法的对象/数据成员的副本tricky()
,因为只有值才是重要的,而不是实际的对象本身。但是打印语句向我保证arg1
,arg2
副本确实在方法内切换。我不明白为什么这不会将信息传递回原始对象,从而切换它们;视为该方法能够成功访问该方法中的arg1.x
和arg1.y
数据成员。
// This class demonstrates the way Java passes arguments by first copying an existing
// object/data member. This is called passing by value. the copy then points(refers)
// to the real object
// get the point class from abstract window toolkit
import java.awt.*;
public class passByValue {
static void tricky(Point arg1, Point arg2){
arg1.x = 100;
arg1.y = 100;
System.out.println("Arg1: " + arg1.x + arg1.y);
System.out.println("Arg2: " + arg2.x + arg2.y);
Point temp = arg1;
arg1 = arg2;
arg2 = temp;
System.out.println("Arg1: " + arg1.x + arg1.y);
System.out.println("Arg2: " + arg2.x + arg2.y);
}
public static void main(String [] args){
Point pnt1 = new Point(0,0);
Point pnt2 = new Point(0,0);
System.out.println("X1: " + pnt1.x + " Y1: " +pnt1.y);
System.out.println("X2: " + pnt2.x + " Y2: " +pnt2.y);
System.out.println(" ");
tricky(pnt1,pnt2);
System.out.println("X1: " + pnt1.x + " Y1:" + pnt1.y);
System.out.println("X2: " + pnt2.x + " Y2: " +pnt2.y);
}
}