File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
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

Win a copy of REST with Spring (video course) this week in the Spring forum!
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: 45335

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: 24195

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

[Jess in Action][AskingGoodQuestions]
I agree. Here's the link:
subject: Treat an object as a constant within a method
jQuery in Action, 3rd edition