I wonder, In Java How can we create a constant object (but not-reference nor immutable since immutability is a feature to all objects of a class) ?
First:
final MyClass c = new MyClass();
creates a constant reference to non-constant object hence I can do:
c.setData(100);
Second:
String class is a class that all its instances should be constant (a.k.a immutable object). I need to have a kind that I can create from a constant objects and non-constanct objects.
In Other words, How to grant the constant-ness to some objects of a class and remove it from other objects. (without the need to wrap this object inside any wrapper).
I suppose that you want something along the lines of the
constkeyword in C++, which makes an instance of an otherwise mutable class immutable. However, no direct equivalent for this exists in Java.If you control the class, you could define an interface that only exposes the getters and use that interface whenever you need a “const” reference – this would not require any wrapping, but it would be rather cumbersome if you need to do this for a lot of classes.