I would like to know as to whether it is possible in java to treat an object as a constant only within a particular method (constant object) (in short prevent modification to its instance variables only within that particular method).
Thanks & Regards, Shiv
Shiv.. as I know him
Joined: Oct 13, 2005
You can set the parameter as final which stops it being reassigned during the method, but if the instance variables are visible to the method, or if there are visible get and set methods, then the method can change the state of the object.
Joined: Aug 05, 2005
What are you trying to achieve ?
If the 'particular method' is one that you wrote, then it's simply a case of not putting any code in that method to change the object.
If the object's data is all private and can only be changed using setter methods, then it is possible to put code in those methods to work out where the method was called from and ignore the change if it was called from this 'particular method'. This sounds a pretty horrible thing to do though. If you explain exactly what the problem is, maybe someone can suggest an alternative solution.
author and iconoclast