参考:https://www.cnblogs.com/perfy/archive/2012/10/16/2726039.html
Person person = new Person("张三");
Person person;
person = new Person("张三");
此处,person只是一个指向对象的引用,new Person('张三')才是创建了这个对象。
Person person;
person = new Person("张三");
person = new Person("李四");
此处,首先声明了person这个"对象的引用",然后先让它指向"张三",后让其指向"李四"
Person person2 = person;
这句话并不是进行对象的复制,而是让person2也指向了 person指向的对象。
也就说,我们用person2改变值时,也会影响person指向对象的值。如下:
person2.setName("王五");
System.out.println(person.getName()); // 输出"王五"
如果传入方法的是基本类型的东西,你就得到此基本类型的一份拷贝。如果是传递对象,则是传递了那个对象的引用。
详情请看如下代码与注释
package hello;
class Test03
{
public static void main(String[] args)
{
StringBuffer s= new StringBuffer("good");
StringBuffer s2=new StringBuffer("bad");
test(s,s2);
System.out.println("out of test, s is " + s); // 输出'goodhah'
System.out.println("out of test, s2 is " + s2); // 输出'bad'
}
static void test(StringBuffer s,StringBuffer s2)
{
System.out.println(s);
System.out.println(s2);
s2=s; //此时,局部变量s2已与 main中的s2所指向的StringBuffer脱离关系,而是指向了main中s指向的对象
s=new StringBuffer("new"); // 此时,局部变量s已与 main中的s所指向的StringBuffer脱离关系,而是指向了新的StringBuffer对象
System.out.println("after s is assigned to 'new', s is: " + s);
System.out.println("after s2 is assigned to s('good'), s2 is: " + s2);
s.append("hah");
s2.append("hah");
// 此时,局部变量s的操作与main中那两个StringBuffer无关了
// 而s2改变的对象正是 main中的s指向的对象
System.out.println("s is: " + s); // 输出 newhah
System.out.println("s2 is: " + s2); // 输出 goodhah
}
}
参考如上代码,我们发现,实际上JAVA的传递都是传递了值,只不过局部参数中的StringBuffer s其实是一个对于对象的引用。 换句话说,在java中,我们必须拥有一个对象的引用,才能去操作堆中的那个对象。而不能用c++中的思维去认为有"对象"及其"引用"。