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!

2

3 Answers 3

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.

Sign up to request clarification or add additional context in comments.

Comments

1

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

Comments

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.