引用传递的分析

引用传递是java的核心,三个简单程序对引用传递做一个完整的分析。

范例:第一个

class Person{
	public void fun() {
		System.out.printlin("FUN方法" + this);
	}
}
public class ThisDemo {
	public static void main (String args[]){
		Person p1 = new Person();
		System.out.printlin("FUN方法" + p1);
		p1.fun();   //由p1调用了fun方法
		Person p2 = new Person();
		System.out.printlin("FUN方法" + p2);
		p2.fun();   //由p1调用了fun方法
		
	}
}

结果为:30

范例2:字符串的引用传递

public class ThisDemo {
	public static void main (String args[]){
		String str = "hello";
		fun(str);
		System.out.println(str);
	}
	public static void fun(String temp){
		temp = "world";
	}
}

结果:hello  (而此时temp的值为world)

在字符串的世界里,字符串是常量,一旦生成就不会改变。一旦发生改变是生成新的字符串,新的指向。

范例3:

class Message (){
	private String note;
	public void setNote(String note){
		this.note = note;
	}
	public String getNote(){
		return this.note;
	}
}
public class ThisDemo {
	public static void main (String args[]){
		Message msg = new Message();
		msg.setNote("hello");
		fun(msg);
		System.out.printlin(msg.getNote());
	}
	public static void fun(String temp){
		temp.setNote("world");
	}
}

结果:world

对于字符串可以按照基本数据类型进行操作。

猜你喜欢

转载自blog.csdn.net/weixin_38266599/article/details/81458875