java调用和引用_java笔记——值调用和引用调用

/*********值调用***********/

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);

}

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值