java在在实例化对象时,是放在栈内存,里面存的只是引用,实际成员变量是存在堆内存里,所以直接交换类其实只是复制了一份引用,成员变量的值并没有改变....
public class ParamOfMethodTest {
public static void main(String[] args) {
// TODO Auto-generated method stub
Employee e1 = new Employee(2, 666);
Employee e2 = new Employee(3, 999);
System.out.println("交换之前的参数:");
System.out.println("e1>>>>>" + e1.toString());
System.out.println("e2>>>>>" + e2.toString());
swap(e1, e2);
System.out.println("交换之后的参数:");
System.out.println("e1>>>>>" + e1.toString());
System.out.println("e2>>>>>" + e2.toString());
}
public static void swap(Employee e1, Employee e2) {
int x = e1.getId();
double y = e1.getSalary();
e1.setId(e2.getId());
e1.setSalary(e2.getSalary());
e2.setId(x);
e2.setSalary(y);
}
}
class Employee {
private int id;
private double salary;
public Employee(int id, double salary) {
this.id = id;
this.salary = salary;
}
public void setId(int id) {
this.id = id;
}
public void setSalary(double salary) {
this.salary = salary;
}
public int getId() {
return this.id;
}
public double getSalary() {
return this.salary;
}
public String toString() {
return "员工的编号: " + id + " 工资: " + salary;
}
}
public class ParamOfMethodTest {
public static void main(String[] args) {
// TODO Auto-generated method stub
Employee e1 = new Employee(2, 666);
Employee e2 = new Employee(3, 999);
System.out.println("交换之前的参数:");
System.out.println("e1>>>>>" + e1.toString());
System.out.println("e2>>>>>" + e2.toString());
swap(e1, e2);
System.out.println("交换之后的参数:");
System.out.println("e1>>>>>" + e1.toString());
System.out.println("e2>>>>>" + e2.toString());
}
public static void swap(Employee e1, Employee e2) {
int x = e1.getId();
double y = e1.getSalary();
e1.setId(e2.getId());
e1.setSalary(e2.getSalary());
e2.setId(x);
e2.setSalary(y);
}
}
class Employee {
private int id;
private double salary;
public Employee(int id, double salary) {
this.id = id;
this.salary = salary;
}
public void setId(int id) {
this.id = id;
}
public void setSalary(double salary) {
this.salary = salary;
}
public int getId() {
return this.id;
}
public double getSalary() {
return this.salary;
}
public String toString() {
return "员工的编号: " + id + " 工资: " + salary;
}
}