Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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:

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!

like image 785
Egor Avatar asked Aug 14 '11 11:08

Egor


2 Answers

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.

like image 125
Armen Tsirunyan Avatar answered Nov 19 '22 22:11

Armen Tsirunyan


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

like image 35
Matten Avatar answered Nov 20 '22 00:11

Matten