本帖最后由 黑马刘涛 于 2012-7-17 12:07 编辑
java里是传值。- package com.itcast.test;
- public class JavaApp {
- /**
- * @param args
- */
- public static void main(String[] args) {
- // TODO Auto-generated method stub
- Yinyong ya=new Yinyong("Zhangsan");
- Yinyong yb=new Yinyong("Lisi");
- swap(ya,yb);//众所周知,类是引用类型,为什么这个函数无效?
- System.out.println("a="+ya.name+" b="+yb.name);
- Change(ya);//而这个函数却有效?
- System.out.println(ya.name);
- }
- public static void swap(Yinyong y1,Yinyong y2) //将ya,yb的值传给了局部变量y1,y2,结果只是y1,y2交换了值,这两个变量在函数生命期结束时结束。
- {
- Yinyong temp=y1;
- y1=y2;
- y2=temp;
- }
- public static void Change(Yinyong y)
- {
- y.name="Wangwu";
- }
- }
- class Yinyong
- {
- String name;
- Yinyong(String name)
- {
- this.name=name;
- System.out.println(this.name);
- }
- }
复制代码 修改一下:- package com.itcast.test;
- public class JavaApp {
- /**
- * @param args
- */
- public static void main(String[] args) {
- // TODO Auto-generated method stub
- Yinyong ya=new Yinyong("Zhangsan");
- Yinyong yb=new Yinyong("Lisi");
- //swap(ya,yb);//众所周知,类是引用类型,为什么这个函数无效?
-
- Yinyong temp = ya;
- ya = yb;
- yb = temp;
- System.out.println("a="+ya.name+" b="+yb.name);
- Change(ya);//而这个函数却有效?
- System.out.println(ya.name);
- }
-
- /*public static void swap(Yinyong y1,Yinyong y2) //将ya,yb的值传给了局部变量y1,y2,结果只是y1,y2交换了值,这两个变量在函数生命期结束时结束。
- {
- Yinyong temp=y1;
- y1=y2;
- y2=temp;
- }
- */
-
- public static void Change(Yinyong y)
- {
- y.name="Wangwu";
- }
- }
- class Yinyong
- {
- String name;
- Yinyong(String name)
- {
- this.name=name;
- System.out.println(this.name);
- }
- }
复制代码 |