Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Class variable: public access read-only, but private access r/w

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?

like image 835
th3falc0n Avatar asked Nov 28 '22 08:11

th3falc0n


2 Answers

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

like image 141
MrSmith42 Avatar answered Dec 04 '22 16:12

MrSmith42


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.
like image 29
Subhrajyoti Majumder Avatar answered Dec 04 '22 15:12

Subhrajyoti Majumder