6、创建一个对象提供swap方法,和test方法,test传入两个基本数据类型参数和一个引用类型参数,分别对它们进行swap,并查看结果。
public class Main
{
public static void main(String[] args)
{
One one = new One();
int a = 10, b = 999;
System.out.println("swap方法之前的a = "+a+", b = "+b);
one.swap(a,b);
System.out.println("swap方法之后的a = "+a+", b = "+b);
//结果,并没有改变外面的a和b
System.out.println("—————分割线——————");
//以下采用传入实例的方法,也就是引用类型变量
Two two = new Two(a,b);
System.out.println("swap方法之前的two.a = "+two.a+", two.b = "+two.b);
one.swap(two);
System.out.println("swap方法之后的two.a = "+two.a+", two.b = "+two.b);
//结果,two引用的也改变了,
}
}
class One
{
//基本数据类型
public void swap(int a, int b)
{
var tmp = a;
a = b;
b = tmp;
System.out.println("swap方法里的a = "+a+" , b = "+b);
}
//重写一个swap方法
public void swap(Two two)
{
var tmp = two.a;
two.a = two.b;
two.b = tmp;
System.out.println("swap方法里的a = "+two.a+" , b = "+two.b);
}
}
class Two
{
int a ,b;
public Two(int a, int b)
{
this.a = a;
this.b = b;
}
}
