jQuery in Action, 3rd edition
The moose likes Beginning Java and the fly likes Treat an object as a constant within a method Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Treat an object as a constant within a method" Watch "Treat an object as a constant within a method" New topic

Treat an object as a constant within a method

sivakumar k r

Joined: Jan 17, 2007
Posts: 4

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.. as I know him
Campbell Ritchie

Joined: Oct 13, 2005
Posts: 46378

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

Joined: Aug 05, 2005
Posts: 3742
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.

Ernest Friedman-Hill
author and iconoclast

Joined: Jul 08, 2003
Posts: 24199

You can use interfaces to present both "changeable" and "unchangeable" views of a class.

[Jess in Action][AskingGoodQuestions]
I agree. Here's the link: http://aspose.com/file-tools
subject: Treat an object as a constant within a method
It's not a secret anymore!