in the above code, 'i' is private to class abc, and method show() is public which is accessing private member i. Now class pqr extends class abc, and so it inherits the public method show() but not the private member i. Buut still, an object of pqr can access the variable i through the show() method. Isnt this contradictory to the definition of 'private'?
When the compiler's not happy, ain't nobody happy.
i dont get it, what i used to think is, once a class has been inherited everything that can be inherited (depending on the access specifiers) gets included in the subclass definition and the private things are completely invisible. So now, this code proves that when an object of type pqr is instantiated, memory WILL be allocated for the varaible 'i' although it is not inherited!!!I hope thats not too confusing..
The variable 'i' is still part of a pqr object because a pqr object is also an abc object.
Look at this structure:
Even though x is declared private in the Parent, the child object still needs needs (and has) the value. Otherwise calling getX() on a Child would not work. And in your code, the show() method would not work. It uses the 'i'. While the pqr class cannot directly access 'i', it still exists within it since it is part of an abc object and is used by pdr when its doing abc stuff.
If I wanted to override something in the Child object, say that x is always set to three times the passed in value, I can do this:
Does that help? [ August 18, 2008: Message edited by: Mark Vedder ]
So does this mean that whenever a subclass is instantiated, memory will be allocated even for the private members of the superclass even though they are not logically a part of the subclass...or are they?!
yes of course, so i cannot declare any new methods in the subclass that would access the private members of the superclass, but that is my question! I think it would not be ethical enough to write functions in the superclass that manipulate the private data and then use them in the subclass, right?
Joined: Oct 13, 2005
Originally posted by Janardan Kelkar: I think it would not be ethical enough to write functions in the superclass that manipulate the private data and then use them in the subclass, right?
Of course you can. If you have a public method which manipulates private fields in the superclass, you can use that method anywhere. It automatically reappears in the subclasses (unless overridden), because a subclass IS-A superclass. [ August 18, 2008: Message edited by: Campbell Ritchie ]