• Post Reply Bookmark Topic Watch Topic
  • New Topic

Access to private members  RSS feed

 
Greenhorn
Posts: 18
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Can the object refernce be used to access a private member?
If so in what situations?
 
author and iconoclast
Sheriff
Posts: 24217
38
Chrome Eclipse IDE Mac OS X
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Only from code in the same class; any instance of class X can access the private members of any other instance of class X, but no code in any other classes can.
 
vijayk kumar
Greenhorn
Posts: 18
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Yes , I get it .Now I will try with an example.
 
Ranch Hand
Posts: 199
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
But is not illegal to happen. I mean private variables should only available for owner only.

Is it a bug or an expected behaviour.
[ July 31, 2006: Message edited by: Rewa Dev ]
 
author
Sheriff
Posts: 14112
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
It's expected behaviour.

The reason to make fields private is so that code outside the class doesn't get coupled to implementation details.

With other words, the purpose of access modifiers is mainly to manage the static structure of the source code, not to manage runtime dependencies of objects.

Does that sound reasonable?
 
Ernest Friedman-Hill
author and iconoclast
Sheriff
Posts: 24217
38
Chrome Eclipse IDE Mac OS X
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Originally posted by Rewa Dev:

Is it a bug or an expected behaviour.


It is definitely expected behavior. Some languages (Java, C++, and others) have class-based encapsulation, in which the class is the level of protection. Others (Ruby is a good example) have object-based encapsulation, in which one object can't call the private members of another; this is rather rarer. Both have their advantages; note that writing comparison methods, clone methods, etc, can be difficult in object-based encapsulation systems.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!