gpt4 book ai didi

java - 为什么在将对象传递给函数时未设置引用

转载 作者:行者123 更新时间:2023-12-01 23:00:03 25 4
gpt4 key购买 nike

我有两个类(class),如下包 com.test;

public class TestObject {
private String id;
private String name;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}

public void printValues() {
System.out.println("ID = "+id);
System.out.println("Name = "+name);
}
}

package com.test;

public class Test {

public void test1() {
TestObject to = new TestObject();
test2(to);
to.printValues();

TestObject to2 = null;
to2 = test2(to2);
to2.printValues();
}

public TestObject test2(TestObject _to) {
if(_to == null) {
_to = new TestObject();
_to.setId("System ID");
_to.setName("System Name : "+new java.util.Date());
} else {
_to = new TestObject();
_to.setId("Some ID");
_to.setName("Some Name : "+new java.util.Date());
}
return _to;
}

public static void main(String[] args) {
Test test = new Test();

test.test1();
}
}

当我运行此代码时,我得到以下输出

ID    = null
Name = null
ID = System ID
Name = System Name : Wed May 07 10:38:22 IST 2014

如果对象为 null,那么我是从函数创建并从函数返回的,那么为什么它给我 null?

请帮助我

提前致谢。

最佳答案

您正在方法中创建一个新对象,因此您的旧对象不会被更新,请修改您的代码:

public void test1() {
TestObject to = new TestObject();
to = test2(to); // THIS line, to receive the object you created in test2()
to.printValues();

TestObject to2 = null;
to2 = test2(to2);
to2.printValues();
}

关于java - 为什么在将对象传递给函数时未设置引用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23509216/

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