In my current project I have a class which stores its Instance in a variable. This Instance should be accesible by all other classes in the project, but it may only be altered by its own class.
How can I achieve this?
In my current project I have a class which stores its Instance in a variable. This Instance should be accesible by all other classes in the project, but it may only be altered by its own class.
How can I achieve this?
Write a public
getter but no public
setter. And the field itself private
In short that is called immutable object
, state of Object
cannot change after it is constructed.
String
is a common example of immutable Class
.
Make a class
immutable
by following-
overridden
- make the class
final
, or use
static
factories and keep constructors private.private
and final
no-argument constructor
combined with subsequent
calls to setXXX
methods.setXXX
methods, but any method which can change
stateSomeone suggests "public getter but no public setter for the private field."
Caution: This would only work if the field is primitive type.
If it is an object with setters, the content can still be modified; thus not read-only.
It will be interesting to see Java language provide some constructs to make a return type read-only without having to do a deep-copy / clone.
i'm imaging like ReadOnly getEmployee() { ...}
The boilerplate code for instantiating a singleton can be found in many places, see for example http://www.javacoffeebreak.com/articles/designpatterns/index.html
Be aware that many consider the singleton to be an antipattern because it's pretty hard to get rid of once your application is littered with references to the singleton.