下面是我在JAVA中幾乎沒有疑問的代碼,沒有通過引用或通過地址傳遞。那麼爲什麼調用方法後輸出會發生變化?還想知道方法調用後JAVA的內部機制?調用函數並將對象作爲參數傳遞給它時,JAVA的行爲是什麼?
class Language
{
String languageID;
String name;
public Language(){}
public Language(String id, String name)
{
this.languageID = id;
this.name = name;
}
@Override
public String toString() {
return "Language id-->" + languageID + " Name-->" + name;
}
}
public class SwapDemo {
public static void swap()
{
int a = 10, b= 5;
System.out.println("Before Swap : A-"+a+" B-"+b);
a = a+b;
b = a-b;
a = a-b;
System.out.println("After Swap : A-"+a+" B-"+b);
a = a^b;
b = a^b;
a = a^b;
System.out.println("After Swap : A-"+a+" B-"+b);
}
public static void swap(Language e1, Language e2)
{
Language temp = new Language();
temp = e1;
e1 = e2;
e2 = temp;
}
public static Language method(Language addit)
{
addit.name = "C++";
addit = new Language();
addit.name = "Harshal";
return addit;
}
public static void main(String[] args) {
Language l1 = new Language("1", "C");
Language l2 = new Language("2", "Java");
System.out.println("Before swap of employees");
System.out.println("Language 1-----> "+l1.toString());
System.out.println("Language 2-----> "+l2.toString());
swap(l1, l2);
System.out.println("After swap of employees");
System.out.println("Language 1-----> "+l1.toString());
System.out.println("Language 2-----> "+l2.toString());
Language t = method(l1);
System.out.println("Changing "+ l1.name);
System.out.println("Changing "+ t.name);
}
}
其實答案已經在這裏:http://stackoverflow.com/questions/40480/is-java-pass-by-reference?rq=1 – Woody