/*********值调用***********/
class CallbyValue{
void change(int a,int b)
{
a*=a;
b+=b;
}
}
class test2
{
public static void main(String[] args)
{
int i=10;
int j=20;
System.out.println("Before call i= "+i+"\t"+"j="+j);
CallbyValue obj=new CallbyValue();
obj.change(i,j);
System.out.println("After call i= "+i+"\t"+"j="+j);
}
}
/********引用调用************/
class Test{
int i;
int j;
Test(int a,int b) //构造函数不能加修饰符,切记
{
i=a;
j=b;
}
void change(Test obj) //对象引用作为形参
{
obj.i*=obj.i;
obj.j+=obj.j;
}
}
class Callbyref
{
public static void main(String[] args)
{
Test obj1=new Test(10,20);
obj1.change(obj1); //注意这里,将对象引用obj1作为实参传递个obj1的方法change
System.out.println("After call obj1.i= "+obj1.i+"\t"+"obj1.j="+obj1.j);
}
}
/************对象作为返回值**************/
class Test{
int i;
int j;
Test(int a,int b)
{
i=a;
j=b;
}
Test change(Test obj)
{
obj.i*=obj.i;
obj.j+=obj.j;
return obj;
}
}
class Callbyref
{
public static void main(String[] args)
{
Test obj1=new Test(10,20);
Test obj2=new Test(6,8);
Test obj3;
obj1.change(obj1);
obj3=obj2.change(obj2);
System.out.println("After call obj1.i= "+obj1.i+"\t"+"obj1.j="+obj1.j);
System.out.println("After call obj1.i= "+obj3.i+"\t"+"obj1.j="+obj3.j);
}
}
/********改进版************/
class Test{
int i;
int j;
Test(int a,int b)
{
i=a;
j=b;
}
Test change(Test obj)
{
obj.i*=i;
obj.j+=j;
return obj;
}
}
class Callbyref
{
public static void main(String[] args)
{
Test obj1=new Test(10,20);
Test obj2=new Test(6,8);
Test obj3;
obj1.change(obj1);
System.out.println("After call obj1.i= "+obj1.i+"\t"+"obj1.j="+obj1.j);
obj3=obj2.change(obj1);
System.out.println("After call obj1.i= "+obj3.i+"\t"+"obj1.j="+obj3.j);
obj3=obj2.change(obj2);
System.out.println("After call obj1.i= "+obj3.i+"\t"+"obj1.j="+obj3.j);
}
}