Why does JAVA only have value transfer? The following code
public class TestSwap {
public static void main(String... args){
Student1 s1 = new Student1(20,"小周");
Student1 s2 = new Student1(13,"瑞瑞");
TestSwap swap = new TestSwap();
swap.swap(s1,s2);
// swap.swap1(s1,s2);
System.out.println("s1:"+s1.getName());
System.out.println("s2:"+s2.getName());
}
private void swap(Student1 x, Student1 y){
Student1 temp = x;
x = y;
y = temp;
System.out.println("x:"+x.getName());
System.out.println("y:"+y.getName());
}
private void swap1(Student1 x, Student1 y){
String temp = x.getName();
x.name = y.getName();
y.name = temp;
System.out.println("x:"+x.getName());
System.out.println("y:"+y.getName());
}
public static class Student1{
int age;
String name;
public Student1(){
}
public Student1(int age, String name) {
this.age = age;
this.name = name;
}
public String getName() {
return name;
}
}
}
The output result of calling swap | x: Ruirui, y: Xiaozhou, s1: Xiaozhou, s2: Ruirui |
---|---|
The output result of calling swap1 | x: Ruirui, y: Xiaozhou, s1: Ruirui, s2: Xiaozhou |
The above output description
- A method can change the state of an object parameter . (The swap1 method allows the name of the Student object to be exchanged)
- A method cannot let the object parameter refer to a new object . (The swap method cannot make an object reference point to another object)