• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Treat an object as a constant within a method

 
sivakumar k r
Greenhorn
Posts: 4
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
 
Campbell Ritchie
Sheriff
Pie
Posts: 49796
69
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 3742
16
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Marshal
Pie
Posts: 24212
35
Chrome Eclipse IDE Mac OS X
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You can use interfaces to present both "changeable" and "unchangeable" views of a class.

 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic