• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Regarding access to private members.

 
Srinivasa Raghavan
Ranch Hand
Posts: 1228
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hello All,
This was my understanding regarding access to private members in a class.
What i thought was a private member cannot be accessed using any object instance. like


except it can only be called from member functions in a class.

In the above code although t1 is a instance of test. the method print() can be called like t1.print(). The same concept will not work when the print is called througn an instance of test from some other class.

Can anyone throw some light on this.
 
David Harkness
Ranch Hand
Posts: 1646
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Private members can be accessed only by the class itself -- not just instances of that class accessing private members of the same instance but any method of that class.

Static methods (like main in your example) can access any private members of instances of the class as well as private static members of the class. Instance methods can access any private member (static or instance) of that class.

The key is that access level (private, protected, and package [aka default]) applies to the class as a whole, not to instances of the class. Here's a concrete example that shows the different forms.There is no way to lock out access to one Thing by another Thing. But since you're writing Thing, you can control the code to ensure Things don't access each other's internals if you want.
 
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
The rule is very simple: any code inside a class can access any member method or variable, private or otherwise, in any instance of that class. This includes static methods, and it also includes code in which one instance of a class manipulates another instance of the same class. It even includes private static members.

C++ has essentially the same rule (although nested classes are treated differently.) Ruby is utterly different: in Ruby, objects are prevented from accessing one another's private members, even if they belong to the same class!
 
Srinivasa Raghavan
Ranch Hand
Posts: 1228
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
This is crystal clear. Thanks David & Ernest.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic