No, it shouldn't.
Java is always pass-by-value, but that value itself is a reference. So if you call a method which alters data of that particular object, it is reflected to all methods retrieving data from that particular object.
A possible solution to this problem is to make immutable types. There are classes which already implement this, for instance, all classes from the java.time
package are immutable. All 'setters' of those classes return a fresh copy of the instance, with the specified value set. An example may be LocalDate::plusDays
.
Here is a little example of the difference between pass-by-value and pass-by-reference.
Take a look at this code.
void main() {
Dog myLittleDog = new Dog("Brutus");
change(myLittleDog);
System.out.println(myLittleDog.getName());
}
void change(Dog aDog) {
aDog = new Dog("Jack");
}
What happens here? We pass our dog named "Brutus" to the change
method. Within this method, we replace Brutus with a new Dog named "Jack". If we print the name of myLittleDog
, what will be his name? Will it be "Jack"?
The answer is no. The value of the reference to the dog is copied, and is available within the change
method under the name aDog
. Both myLittleDog
and aDog
are referring to the same actual dog object in memory. But now the change
method reassigns aDog
with a new
object. At this moment, the variables myLittleDog
and aDog
both refer to distinct objects. Once the change
method exits, the variable aDog
is unreachable and Jack
is garbage collected. myLittleDog
is still called "Brutus".
Conversely, this wouldn't be the case if Java was pass-by-reference. Then reassignment of aDog
would also mean reassignment of myLittleDog
.
See also: What's the difference between passing by reference vs. passing by value?
But then why is my selectedService
still mutated?
Although values of references are copied when they are passed to methods, doesn't that mean that objects cannot change (that is, be modified). Suppose I give you a copy of my house key. You access my house and move the couch to the kitchen. Then if I enter my house, I will see that the couch has been moved. The reference value is copied, but everyone accessing the referenced object (the house), will see modifications to it.