您的位置:首页 > 编程语言 > Java开发

JAVA中的引用传递

2016-01-25 00:48 495 查看
在介绍常见的引用传递之前先看一下对象的引用传递操作,所谓引用传递就是把堆内存空间的使用权交给其他的对象,就是为堆内存空间起了一个别名。引用传递传递的是对象的地址,通过以下引用传递在内存中的变化体会一下何为传递的是地址。

class Person{

public String name;

public int age;

……

Person(String name,int age){

this.name = name;

this.age = age;

}

Person(){

}

}

public class Test{

public static void main(String args[]){

Person per1= null;

Person per2 = null;

per1 = new Person();

per2 = new Person("李四",0);

per2 = per1;

per1.name="张三";

per1.age=30;

per2.age=33;

}

}



下面看一下常见的参数传递中,引用类型的传递。

class Demo {

public int x=10;

}

public class test{

public static void main(String args[]){

Demo d = new Demo();

d.x=30;

fun(d);

}

public fun(Demo temp){

temp.x=100;

}

}



在所有的类中,String类型例外String类型的对象永远不变。代码如下:

class Test{

public static void main(String args[]){

String str="hello";

fun(str);

system.out.println(str);

}

public static void fun(String temp){

temp = "world";

}

}

此时输出依然是hello。

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: