This week's book giveaway is in the OCAJP forum.
We're giving away four copies of Programmer's Guide to Java SE 8 Oracle Certified Associate (OCA) and have Khalid A Mughal & Rolf W Rasmussen on-line!
See this thread for details.
Win a copy of Programmer's Guide to Java SE 8 Oracle Certified Associate (OCA) this week in the OCAJP forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

create instance variable

 
sathi jogi
Greenhorn
Posts: 14
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
How to create an array instance variable, so that it will be allowed to modify only with in that instance object and visible to other objects but it should not allow to modify that array object values by other instance objects?
 
Peter Chase
Ranch Hand
Posts: 1970
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I am struggling to understand the question you have posed, but I think you are asking how one can give access to an array, but not allow the contents of the array to be changed.

If that is the question, the answer is you can't.

If you have a reference to a Java array, you can always modify the contents of the array. Java arrays are low-level things, more suited to private implementation details of a class than for passing around between classes. You should use classes, including Collections(*), in preference to arrays, most of the time.

If you want to provide the sort of facilities you're talking about, you should wrap the array up in a class. The array would be a private instance variable of the class. The class would then provide methods to allow appropriate access to the data in the array (e.g. private setters, public getters).

(*) Of course, Collections are mostly implemented using arrays internally. But that's the sort of private implementation detail for which arrays are well-suited.
[ September 05, 2007: Message edited by: Peter Chase ]
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic