實(shí)踐1:參數(shù)以by value方式而非by reference方式傳遞
Java中的參數(shù)以by value方式傳遞,舉個(gè)例子:
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函數(shù)中的基本數(shù)據(jù)類型i的值在調(diào)用modifyPoint后并沒被改變撩荣,可見傳給參數(shù)j的是i的一份副本敞嗡。但是對(duì)象p的值被修改了长窄,說明pt拿到的是指向point對(duì)象實(shí)例的引用的一份副本娱据,p和pt指向的是同一個(gè)對(duì)象,它看起來像這樣
因此在調(diào)用 pt.setLocation(5,5); //1 后抗楔,該P(yáng)oint對(duì)象被修改了俊扭。