From the effective Java book it states that "An object can always be reused if it is immutable".
String s = "shane";
String p = "shane";
This version uses a single String instance
, rather than creating a new one
each time it is executed. Furthermore, it is guaranteed that the object will be
reused by any other code running in the same virtual machine that happens to contain
the same string literal.
What about the below final class which is also immutable?. Can the Point Object be re-used?.
public final class Point {
private final int x, y;
public Point(int x, int y) {
this.x = x;
this.y = y;
}
public int getX() { return x; }
public int getY() { return y;
}
Can anyone provide me an example of the above immutable class
where its object/instance can be re-used?. I am just confused on how the re-usability would occur?.
I am able to relate with String
and Integer
Classes, but not with user defined classes.
Immutable class == immutable Object
– Visualize