Meaningless Drivel is fun!
The moose likes Beginning Java and the fly likes Regarding access to private members. Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Regarding access to private members." Watch "Regarding access to private members." New topic

Regarding access to private members.

Srinivasa Raghavan
Ranch Hand

Joined: Sep 28, 2004
Posts: 1228
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.

Thanks & regards, Srini
MCP, SCJP-1.4, NCFM (Financial Markets), Oracle 9i - SQL ( 1Z0-007 ), ITIL Certified
David Harkness
Ranch Hand

Joined: Aug 07, 2003
Posts: 1646
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

Joined: Jul 08, 2003
Posts: 24199

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!

[Jess in Action][AskingGoodQuestions]
Srinivasa Raghavan
Ranch Hand

Joined: Sep 28, 2004
Posts: 1228
This is crystal clear. Thanks David & Ernest.
I agree. Here's the link:
subject: Regarding access to private members.
It's not a secret anymore!