/*********值調(diào)用***********/
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);
}
}
/********引用調(diào)用************/
class Test{
int i;
int j;
Test(int a,int b) //構(gòu)造函數(shù)不能加修飾符,切記
{
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);
}
}
/********改進(jìn)版************/
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);
}
}
本站僅提供存儲服務(wù),所有內(nèi)容均由用戶發(fā)布,如發(fā)現(xiàn)有害或侵權(quán)內(nèi)容,請
點擊舉報。