I have been reading Effective Java and I have come across the statement that not only can you share immutable objects, but you can share their internals. But, I am struggling to figure out what that really means and an example would surely help as no example is given in the book. I already know that immutable objects can't be changed, such as a String
.
An object is considered immutable if its state cannot change after it is constructed. Maximum reliance on immutable objects is widely accepted as a sound strategy for creating simple, reliable code. Immutable objects are particularly useful in concurrent applications.
In object-oriented and functional programming, an immutable object (unchangeable object) is an object whose state cannot be modified after it is created. This is in contrast to a mutable object (changeable object), which can be modified after it is created.
The immutable objects are objects whose value can not be changed after initialization. We can not change anything once the object is created. For example, primitive objects such as int, long, float, double, all legacy classes, Wrapper class, String class, etc. In a nutshell, immutable means unmodified or unchangeable.
Immutable objects offer a number of advantages for building reliable applications. As we don't need to write defensive or protective code to keep application state consistent, our code can be simpler, more concise, and less error-prone than when we define mutable objects.
Read the book further:
The
BigInteger
class uses a sign-magnitude representation internally. The sign is represented by anint
and the magnitude is represented by anint
array. Thenegate
method produces a newBigInteger
of like magnitude and opposite sign. It does not need to copy the array; the newly createdBigInteger
points to the same internal array as original.
For example if you have a class
public class Vector2d {
private final BigDecimal a;
private final BigDecimal b;
}
Then a
and b
are the "internals" of that class. Since this are instance of BigDecimal
they are immutable. If you implement an operation like setBToZero()
you can simply reuse your instance of a
and don't have to recreate a new one. For example
public Vector2d setBToZero() {
return new Vector2d(a, 0);
}
You share your internal a
and since it is immutable you don't have to worry about changes of your shared state. This is especially useful, when it comes to large objects. If you use interfaces you can implement some operations only by using proxy objects.
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