实践1:参数以by value方式而非by reference方式传递
Java中的参数以by value方式传递,举个例子:
import java.awt.Point;
class PassByValue
{
public static void modifyPoint(Point pt, int j)
{
pt.setLocation(5,5); //1
j = 15;
System.out.println("During modifyPoint " + "pt = " + pt + " and j = " + j);
}
public static void main(String args[])
{
Point p = new Point(0,0); //2
int i = 10;
System.out.println("Before modifyPoint " + "p = " + p + " and i = " + i);
modifyPoint(p, i); //3
System.out.println("After modifyPoint " + "p = " + p + " and i = " + i);
}
}
以上代码的输出为
main函数中的基本数据类型i的值在调用modifyPoint后并没被改变,可见传给参数j的是i的一份副本。但是对象p的值被修改了,说明pt拿到的是指向point对象实例的引用的一份副本,p和pt指向的是同一个对象,它看起来像这样
因此在调用 pt.setLocation(5,5); //1 后,该Point对象被修改了。