Two Laptop Bag
The moose likes Java in General and the fly likes Not so private Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Java in General
Bookmark "Not so private" Watch "Not so private" New topic

Not so private

Laurent Leonard
Ranch Hand

Joined: May 15, 2001
Posts: 35
I've a class with a private member. In this class I create an instance of this class. And I'm quite surpised that I can access the private member through this instance.
Here is the example.
public class MyClass
private Object myPrivateMember;
public MyClass()
myPrivateMember = new Object();
public void createInstance()
MyClass instanceOfMyClass;
instanceOfMyClass = new MyClass();
// This is the surprising line because there is no problem
instanceOfMyClass.myPrivateMember = new Object();
I was thinking that, when a member is private, the only way to access it, is through a so-called set and get method. (These methods access to it via this.thePrivateMember).
Can someone explain me why this is allowed ???
Thanks in advance.

Laurent Leonard

Dave Vick
Ranch Hand

Joined: May 10, 2001
Posts: 3244
I think you're confusing two related things. A private member of a class can only be accessed from within the class itself. Check out the JLS sect. 6.6.8 for more info and a good example.
The setter and getter methods are used because it makes good object oriented sense to make the data private and only allow access through methods that can control how the members are changed. Normally they are used for access by classes other than the one that defines the member. From within the defining class it is perfectly legal to do whatever you like to the classes data members (although it is usually easier and better looking to use your accessor methods).
Think of it this way... you create accessor methods in the same class as you define the private member, so methods in the same class have to have access to the variable. There is nothing special in the name of the accessor methods that gives them access where other methods dont. You could call your accessor method 'fred' or anything you like and as long as they are in the same class as the member they will have access.
hope that helps

Sun Certified Programmer for the Java� 2 Platform

Peter den Haan
Ranch Hand

Joined: Apr 20, 2000
Posts: 3252
Put differently, the member variable is private to the class, not private to the object. And if this alarms you, wait until you see the access rules for inner classes
- Peter

[This message has been edited by Peter den Haan (edited September 19, 2001).]
I agree. Here's the link:
subject: Not so private
It's not a secret anymore!