Say I have code
if(some statement){
object1.setSomeField("abc");
}
Could I do this?
public void methodToSetField(SomeObject object1){
//provide some logic for setting
object1.setSomeField("abc")
}
if(some statement){
this.methodToSetField(object1);
}
Now my question is, if I want to replace the first piece of code, with the method do I need to return object1 or is it enough to set it.
No you don't have to , as you are working on the same memory object. So the calling code, if uses the values after calling your method, it should see the updates.
That is fine to do. In java, when you pass in an object, you don't actually pass in the "object" but rather the reference (or pointer) to the object.
Any modifications you make will directly alter the object you've passed in as long as you don't do something like:
SomeObject someObject = new SomeObject();
EDIT: Is Java "pass-by-reference" or "pass-by-value"?
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With