定义类:
class Student {
String name;
int sex;
public Student(String name, int sex) {
this.name = name;
this.sex = sex;
}
@Override
public String toString() {
return "Student{" +
"name='" + name + '\'' +
", sex=" + sex +
'}';
}
}
public class demo {
public static void main(String[] args) {
int a = 123;
int b = 456;
hand(a, b);
System.out.println(a + " " + b);
Student s1 = new Student("zhang", 18);
Student s2 = new Student("li", 20);
hand(s1, s2);
System.out.println(s1);
System.out.println(s2);
Student s3 = new Student("zhao", 19);
Student s4 = new Student("zhou", 21);
hand1(s3, s4);
System.out.println(s3);
System.out.println(s4);
}
//数值交换——失败
private static void hand(int a, int b) {
int t = a;
a = b;
b = t;
}
//类交换——失败
private static void hand(Student s1, Student s2) {
Student s = s1;
s1 = s2;
s2 = s;
}
//交换成功
private static void hand1(Student s1, Student s2) {
Student s = new Student("haha", 9);
s.name = s1.name;
s1.name = s2.name;
s2.name = s.name;
}
}
输出结果: