Initializing a Java object in a separate way: why it won't work

Here is a thing that I cannot say, I am surprised that this will not work, but I am interested to find an explanation for this case. Imagine we have an object:

SomeClass someClass = null; 

And the 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); 

He will print:

 null 

Thank you for your responses!

+7
source share
3 answers

This is not possible to do in java. In C #, you must pass a 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?

By the way, for the same reason, you cannot write a swap function in java that will replace two integers.

+9
source

As Armen said, what you want to do is not possible in this way. Why not use the factory method ?

+1
source

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

The method does not accept the object as a parameter in your case. It accepts a link that points to zero. He then copies this link and points to a new instance of SomeClass . But obviously, the link you passed as a parameter still points to null .

0
source

All Articles