Win a copy of Design for the Mind this week in the Design forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Not so private

 
Laurent Leonard
Ranch Hand
Posts: 35
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Laurent.Leonard@advalvas.be
 
Dave Vick
Ranch Hand
Posts: 3244
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Laurent
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

------------------
Dave
Sun Certified Programmer for the Java� 2 Platform
 
Peter den Haan
author
Ranch Hand
Posts: 3252
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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).]
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic