This week's book giveaway is in the Reactive Progamming forum. We're giving away four copies of Reactive Streams in Java: Concurrency with RxJava, Reactor, and Akka Streams and have Adam Davis on-line! See this thread for details.
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".
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.
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.