我知道类是引用类型,例如我创建了以下类:
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
最佳答案
关于java - String 在 Java 中如何成为引用类型?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51466358/