This week's book giveaway is in the OO, Patterns, UML and Refactoring forum. We're giving away four copies of Refactoring for Software Design Smells: Managing Technical Debt and have Girish Suryanarayana, Ganesh Samarthyam & Tushar Sharma on-line! See this thread for details.
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.
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.
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!