8

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!

Egor
  • 39,695
  • 10
  • 113
  • 130
  • possible duplicate of [Is Java pass by reference?](http://stackoverflow.com/questions/40480/is-java-pass-by-reference) – Mat Aug 14 '11 at 11:03
  • possible duplicate of [Can I pass parameters by reference in Java?](http://stackoverflow.com/questions/1068760/can-i-pass-parameters-by-reference-in-java) – Armen Tsirunyan Aug 14 '11 at 11:03

3 Answers3

10

It's impossible to do in java. In C# you'd pass the parameter using the ref or out 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.

Community
  • 1
  • 1
Armen Tsirunyan
  • 130,161
  • 59
  • 324
  • 434
1

As Armen mentioned, what you want to do is not possible this way. Why not use a factory method?

Matten
  • 17,365
  • 2
  • 42
  • 64
0

And a method that will take this object as a parameter to initialize it:

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.

jFrenetic
  • 5,384
  • 5
  • 42
  • 67