gpt4 book ai didi

java - 引用类型是通过引用复制的吗?

转载 作者:行者123 更新时间:2023-12-02 05:32:11 24 4
gpt4 key购买 nike

是的,仍在学习 Java 基础知识!所以我指的文本说 - 引用类型(除原语之外的所有类型)都是通过引用复制的。现在,我还被告知字符串是引用类型 - 这就是原因 -

String str = "test";
String another_str = "test";

if ( str != another_str )
{
System.out.println("Two strings are different"); // this is printed
}

如果是这样,为什么会发生这种情况 -

package prj_explore_infa_sdk;

public class parent_class {
public String test;
public parent_class (String str){
test = str;
test = "overriden";
}
public parent_class (){
test = "overriden";
}
}

package prj_explore_infa_sdk;

public class child_class extends parent_class{
public static void main(String[] args){
child_class cls = new child_class();
if ( cls instanceof parent_class)
System.out.println("Subclass is an instanceof parent class");
String start = "nice";
parent_class pclass = new parent_class(start);
start = "changed";
System.out.println("Start : " + start + ", pclass.test : " + pclass.test);
}

}

这打印 -

Subclass is an instanceof parent class
Start : changed, pclass.test : overriden

如果复制了 String 引用,为什么这不会更改 pclass 对象的成员测试?

最佳答案

在 Java 中,一切都是按值传递的。

对于引用类型,传递的值恰好是对象引用。

您遇到的问题是

开始=“已更改”

正在为方法的 start 变量分配一个 new String 对象引用,而 pclass 仍然具有 old String 对象引用。

顺便说一句,String 对象是不可变的,无法修改。

关于java - 引用类型是通过引用复制的吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25417730/

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