You're not doing the same thing with BigInteger
- you're calling the add
method which returns a reference to a new BigInteger
, and you're assigning that value back to big
.
Your Sample.add
method changes the existing object instead:
public Sample add(int number){
this.number += number;
return this;
}
If you changed it to return a reference to a new object, it would behave like BigInteger
:
public Sample add(int number){
Sample sample = new Sample();
sample.setNumber(sample.number + number);
return sample;
}
However, your Sample
class is fundamentally mutable at the moment, unlike BigInteger
. No operations on BigInteger
change the state of an existing object; instead, they all create new objects. If you want to replicate that behaviour in Sample
, you'd write it something like this:
public final class Sample {
private final int number;
public Sample(int number) {
this.number = number;
}
public int getNumber(){
return number;
}
public Sample add(int number){
return new Sample(this.number + number);
}
}
It's important to understand that you're never passing objects around in Java - only references which are used to navigate to objects. So for example:
StringBuilder a = new StringBuilder();
StringBuilder b = a;
b.append("hello");
System.out.println(a); // Prints hello
Here there's a single StringBuilder
object, but both variables (a
and b
) have values which refer to the same object. Any changes made via one variable are still visible through the other variable. (See this Stack Overflow answer for more about this.)