Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I create a constant object in Java?

Tags:

java

How do I create a reference to a constant object?

final Myclass obj = new Myclass();

does not work, it says obj(the reference) should not be re-assigned but we can still change the object referred.

I want to ensure that the object itself does not change once constructed.

like image 640
gameover Avatar asked Nov 28 '22 01:11

gameover


1 Answers

Just make it immutable (like String is). Or wrap it in another object which restricts access to mutators of the object in question (like Collections.unmodifiableList() and consorts do).

like image 151
BalusC Avatar answered Dec 04 '22 22:12

BalusC