• Post Reply Bookmark Topic Watch Topic
  • New Topic

Why is a private member of a class accessible using a class object in main()  RSS feed

 
Siddhant Agarwal
Greenhorn
Posts: 9
1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator


Why I am able to access a private member of a class using an instance of the same class? Doesn't that beat the purpose of data hiding?
I came across this example while reading through book "OCA Study Guide by Jeanne Boyarsky and Scott Selikoff". This example is given under Chapter 1 - Java Building Blocks, topic "Order of Initialization".
 
Paul Clapham
Sheriff
Posts: 22828
43
Eclipse IDE Firefox Browser MySQL Database
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Not at all. "private" means "access restricted to this class only". Not "access restricted to this object only".

If you think about it, you'll see that the compiler can't possibly implement the latter rule. When an object of class Chick accesses a private member of class Chick, there's no way for it to tell whether that member belongs to that object or to some other object of class Chick. However the former rule, the one which actually applies, it's possible for the compiler to implement that one.

In the example you posted, it's code in the Chick class which is accessing the "name" member of some Chick object -- and it doesn't matter which Chick object. Even code in static methods of Chick can do that, as the example shows.
 
Paul Clapham
Sheriff
Posts: 22828
43
Eclipse IDE Firefox Browser MySQL Database
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
And, welcome to the Ranch!
 
Siddhant Agarwal
Greenhorn
Posts: 9
1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I think I understand now. I went through various posts on stack overflow as well discussing the same thing and then tried with a sample code where the object of Chick class was created in some other class. So as long as the object uses the private member within the class, it works. If I create the Chick object in some other class, and try to access the private member of Chick, it shows me an error.
Thanks!
 
Paul Clapham
Sheriff
Posts: 22828
43
Eclipse IDE Firefox Browser MySQL Database
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Writing sample code to investigate language features, that's a good strategy. Glad it worked out for you!
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!