if java is always pass variables by reference, why does eclipse generate the bean with out any consideration.
instead of:
return myStr;
needs to be
return new String(myStr);
no?
Edit
Ok, my example was bad.
lets leave eclipse, When I want to return a Custom object. Do i need to create a “copy constructor” and return it, like that:
return new MyCustomObject(myCustomObject);
class MyCustomObject{
private String str;
public MyCustomObject(String str){
this.str = str;
}
public MyCustomObject(MyCustomObject obj){
this.str = obj.str;
}
}
Must I write that?
No.
In Java, every object variable is a reference. Objects cannot be passed by value, only primitives can (and always are). Well, that’s slightly misleading. The reference is passed by value, but you can think of everything being a reference, just not in a C++ sense.
Perhaps it’s easiest to use an example.
So,
foois a reference to an instance ofSomeObject. WhendoSomethingis called, the value of that reference is copied tobar, so nowfooandbarare references to the sameSomeObject.The line
bar.whatever()callswhateveron the same object thatfoorefers to.bar = new SomeObject()means thatfooandbarnow refer to differentSomeObjectinstances, sosomeOtherMethodis not called on the object thatfoorefers to.This is completely different to C++, where
has a totally different meaning. You really should not ever think of Java in C++ terms.
Regarding your example,
Strings are immutable in Java so it wouldn’t matter even if objects could be passed by value.Regarding your second example, if you want to return an object that the caller cannot use to pollute your internal state then, yes, you need to have a copy constructor (or something equivalent).
For example:
You can choose the appropriate type of return value (normal reference, immutable view or copy) depending on the situation. Any or all of the three options could be appropriate depending on exactly what you are doing.
java.util.Collectionsmakes it easy to get an immutable view of aCollection, but for custom classes you’ll need to do your own immutable-ness.Remember that you only need to do this if there is an issue with mutability. Your
MyCustomObjectexample is still immutable (since the caller cannot change any state in the returnedMyCustomObjectinstance), so the question is still kinda moot.