一、代码

/*
1、可以将多个类写在一个类文件中,但只能有一个类是public类,而且该类的类名必须和类文件名一致。
2、就算MyClass定义在后面,也可以检索到
*/
public class AboutSwap {
// 1:change
public static void change(MyClass myClass){
myClass.setNum(100);
}
// 2:类比于C swap(int *a,int *b)
public static void swapA(MyClass a,MyClass b){
MyClass tmp=a;
a=b;
b=tmp;
}
// 3: 改进版swap
public static void swapB(MyClass a,MyClass b){
Object tmp=a.getNum();
a.setNum(b.getNum());
b.setNum(tmp);
}
public static void main(String[] args){
// change
MyClass e=new MyClass(10);
System.out.println("调用change方法前的值为:"+e.getNum());
change(e);
System.out.println("调用change方法后的值为:"+e.getNum());
//
MyClass a=new MyClass(10);
MyClass b=new MyClass(100);
//
// swapA result
System.out.println("交换swapA之前a的值为:"+a.getNum());
System.out.println("交换swapA之前b的值为:"+b.getNum());
swapA(a,b);
System.out.println("交换swapA之后a的值为:"+a.getNum());
System.out.println("交换swapA之后b的值为:"+b.getNum());
// swapB result
System.out.println("交换swapB之前a的值为:"+a.getNum());
System.out.println("交换swapB之前b的值为:"+b.getNum());
swapB(a,b);
System.out.println("交换swapB之后a的值为:"+a.getNum());
System.out.println("交换swapB之后b的值为:"+b.getNum());
}
}
class MyClass {
private Objectnum;
public MyClass(Object num) {
this.num = num;
}
public Object getNum() {
return num;
}
public void setNum(Object num) {
this.num = num;
}
}