5

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?

2
  • What do you mean with "its instance"? Is there only one instance of the class? (A singleton)
    – flup
    Commented Jan 14, 2013 at 19:04
  • Yes, that is what I meant.
    – th3falc0n
    Commented Jan 14, 2013 at 19:04

4 Answers 4

20

Write a public getter but no public setter. And the field itself private

2
  • 4
    And the field's type must be immutable.
    – Matt Ball
    Commented Jan 14, 2013 at 19:03
  • 1
    If the field's type is not immutable you can always return a deep copy of it instead of a reference to itself to ensure that the field could not be modified by others.
    – MrSmith42
    Commented Sep 30, 2013 at 8:04
4

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-

  • ensure the class cannot be overridden - make the class final, or use static factories and keep constructors private.
  • make fields private and final
  • force callers to construct an object completely in a single step, instead of using a no-argument constructor combined with subsequent calls to setXXX methods.
  • do not provide any methods which can change the state of the object in any way - not just setXXX methods, but any method which can change state
  • if the class has any mutable object fields, then they must be defensively copied when passed between the class and its caller.
2

Someone 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() { ...}

0

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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.