在单独的方法中初始化 Java 对象:为什么这不起作用
有件事我不能说,我很惊讶它不起作用,但无论如何,找到这个案例的解释对我来说很有趣。 想象一下我们有一个对象:
SomeClass someClass = null;
和一个方法,该方法将以该对象作为参数来初始化它:
public void initialize(SomeClass someClass) {
someClass = new SomeClass();
}
然后当我们调用:
initialize(someClass);
System.out.println("" + someClass);
它将打印:
null
感谢您的回答!
Here's a thing that I can't tell I'm surprised it won't work, but anyway it's interesting for me to find the explanation of this case.
Imagine we have an object:
SomeClass someClass = null;
And a method that will take this object as a parameter to initialize it:
public void initialize(SomeClass someClass) {
someClass = new SomeClass();
}
And then when we call:
initialize(someClass);
System.out.println("" + someClass);
It will print:
null
Thanks for your answers!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
在java中这是不可能做到的。在 C# 中,您可以使用
ref
或out
关键字传递参数。 java中没有这样的关键字。您可以查看此问题了解详细信息: Can I pass parameters by reference in Java ?顺便说一句,出于同样的原因,您不能在 java 中编写交换两个整数的交换函数。
It's impossible to do in java. In C# you'd pass the parameter using the
ref
orout
keyword. There are no such keywords in java. You can see this question for details: Can I pass parameters by reference in Java?Incidentally, for that same reason you cannot write a swap function in java that would swap two integers.
正如阿门提到的,你想做的事情是不可能通过这种方式实现的。为什么不使用工厂方法?
As Armen mentioned, what you want to do is not possible this way. Why not use a factory method?
在您的情况下,该方法不将对象作为参数。它需要一个指向 null 的引用。然后它复制此引用并将其指向
SomeClass
的新实例。但显然,您作为参数传递的引用仍然指向 null。The method does not take an object as a parameter in your case. It takes a reference which points to null. Then it copies this reference and points it to a new instance of
SomeClass
. But obviously, the reference that you passed as a parameter still points to null.