gpt4 book ai didi

java - String 在 Java 中如何成为引用类型?

转载 作者:行者123 更新时间:2023-12-03 11:18:42 25 4
gpt4 key购买 nike

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

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

最佳答案

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

method

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

new object

关于java - String 在 Java 中如何成为引用类型?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51466358/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com