首页 > 解决方案 > Java 中的 String 是如何成为引用类型的?

问题描述

我知道类是引用类型,例如我创建了以下类:

class Class {

String s = "Hello";

public void change() {
    s = "Bye";
} }

使用以下代码,我了解这Class是一个引用类型:

Class c1 = new Class(); 
Class c2 = c1; //now has the same reference as c1

System.out.println(c1.s); //prints Hello
System.out.println(c2.s); //prints Hello

c2.change(); //changes s to Bye

System.out.println(c1.s); //prints Bye
System.out.println(c2.s); //prints Bye

现在我想用一个字符串做同样的事情,这是行不通的。我在这里做错了什么?:

String s1 = "Hello";
String s2 = s1; //now has the same reference as s1 right?

System.out.println(s1); //prints Hello
System.out.println(s2); //prints Hello

s2 = "Bye"; //now changes s2 (so s1 as well because of the same reference?) to Bye

System.out.println(s1); //prints Hello (why isn't it changed to Bye?)
System.out.println(s2); //prints Bye

标签: javastringreference

解决方案


在第一种情况下,您正在调用被引用对象的方法,因此被引用对象发生了变化,而不是 2 个引用:

方法

在第二种情况下,您将一个新对象分配给引用本身,然后指向该新对象:

新对象


推荐阅读