2 ms·
Class Rect { final int x, y; //Constructor goes here } Rect r1 = new Rect(1,2); Is this not sufficient to create an immutable rectangle that I can pass
by ashishb 2y ago
Class Rect {
final int x, y;
//Constructor goes here
}
Rect r1 = new Rect(1,2);
Is this not sufficient to create an immutable rectangle that I can pass around safely in a multi-threaded code?
- maleldil 2y agoWhen x and y are primitives, yes. But if they're objects, final only prevents you from re-assigning them. You could still call methods that mutate them.
- loginatnine 2y agoUnless the object is immutable, like String, Integer, Long, ImmutableCollections, etc. Or your own immutable objects.
- ashishb 2y ago> Unless the object is immutable, like String, Integer, Long, ImmutableCollections, etc. Or your own immutable objects. Exactly. You can have immutable primitives. You can have immutable classes. And you can combine them to form thread-safe immutable classes.
- maleldil 2y agoNow you're restricting yourself to a subset of the language. There's nothing stopping someone from adding a mutable member to your "immutable" type later. It's much better to have immutable bindings/references so that nothing that mutates the object can be done through them. Rust does it very well, for example. Even C++ has a good version of this.
- ashishb 2y ago> It's much better to have immutable bindings/references so that nothing that mutates the object can be done through them. Rust does it very well, for example. Even C++ has a good version of this. Yes, that might be superior but even Java is doing better than Go here.