简体   繁体   English

以单独的方法初始化 Java object:为什么这不起作用

[英]Initializing a Java object in a separate method: why this won't work

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:假设我们有一个 object:

SomeClass someClass = null;

And a method that will take this object as a parameter to initialize it:还有一个方法,将这个 object 作为参数来初始化它:

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!感谢您的回答!

It's impossible to do in java.在 java 中是不可能的。 In C# you'd pass the parameter using the ref or out keyword.在 C# 中,您将使用refout关键字传递参数。 There are no such keywords in java. java中没有这样的关键字。 You can see this question for details: Can I pass parameters by reference in Java?详情可以看这个问题: Java中可以通过引用传递参数吗?

Incidentally, for that same reason you cannot write a swap function in java that would swap two integers.顺便说一句,出于同样的原因,您不能在 java 中编写一个交换 function 来交换两个整数。

As Armen mentioned, what you want to do is not possible this way.正如 Armen 所提到的,你想做的事情是不可能的。 Why not use a factory method?为什么不使用工厂方法?

And a method that will take this object as a parameter to initialize it:还有一个方法,将这个 object 作为参数来初始化它:

The method does not take an object as a parameter in your case.在您的情况下,该方法不采用object作为参数。 It takes a reference which points to null.它采用指向 null 的引用。 Then it copies this reference and points it to a new instance of SomeClass .然后它复制此引用并将其指向SomeClass的新实例。 But obviously, the reference that you passed as a parameter still points to null .但显然,您作为参数传递的引用仍然指向null

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM