import java.awt.Point;
class PassByValue
{
public static void modifyPoint(Point pt, int j, String str)
{
j = 15; // <- ? have to check primitive type.
str = "def";
/*************************************************************************************
* 產生了一個 String 型態的 "def" 物件, 並將它的 reference 給 str,
* 所以替換了 str 原本的 reference
************************************************************************************/
pt.setLocation(5,5);
/*************************************************************************************
* 替換了 Point p reference, 但也因為用了"."這個 operator, 它會 dereference,
* 所以它也改變了本身 object 的 value.
***********************************************************************************/
//pt = new Point(5,5); //只修改了 Point pt 的 reference
System.out.println("During modifyPoint: pt = "+pt+", j = "+j+", str = "+str);
}
public static void main(String[] args)
{
Point p = new Point(0,0);
/*************************************************************************************
* 1. new Point(0,0) <- 在記憶體產生了 Point 物件, 且是 Point 型態, 同時產生了 reference
* 2. Point p <- 一個名為 p 的空間, 其型態為 Point,
* 3. "=" 這個 operator 將 Point(0,0) 的 reference 放到了 p 裡面,
* 所以就可以利用 p 裡的 reference 來找到這個物件.
*************************************************************************************/
int i = 10;
String s = new String("abc");
System.out.println("Before modifyingPoint: p = "+p+", i = "+i+", s = "+s);
modifyPoint(p,i,s);
System.out.println("Before modifyingPoint: p = "+p+", i = "+i+", s = "+s);
}
}
Before modifyingPoint: p = java.awt.Point[x=0,y=0], i = 10, s = abc
During modifyPoint: pt = java.awt.Point[x=5,y=5], j = 15, str = def
Before modifyingPoint: p = java.awt.Point[x=5,y=5], i = 10, s = abc
Normal Termination
輸出完成 (耗費 0 秒)。