| Author |
Treat an object as a constant within a method
|
sivakumar k r
Greenhorn
Joined: Jan 17, 2007
Posts: 4
|
|
Hi, 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
|
 |
Campbell Ritchie
Sheriff
Joined: Oct 13, 2005
Posts: 32595
|
|
No. 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.
|
 |
Joanne Neal
Rancher
Joined: Aug 05, 2005
Posts: 3011
|
|
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.
|
Joanne
|
 |
Ernest Friedman-Hill
author and iconoclast
Marshal
Joined: Jul 08, 2003
Posts: 24039
|
|
You can use interfaces to present both "changeable" and "unchangeable" views of a class.
|
[Jess in Action][AskingGoodQuestions]
|
 |
 |
|
|
subject: Treat an object as a constant within a method
|
|
|