下面是我几乎没有疑问的代码,因为在 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);
}
}