Even I got confused, I always assumed that methods follow runtime binding and variables are bound at compile time. This assumption is correct but there is a caveat.
At compile time the most specific method signature visible from the DECLARED class of variable xxx is choosen to bind - the choice set includes all visible inherited methods. (In this case the A's print method is not visible in class B, since it is private)
In Java the symbolic references are bound at compile time. To know what happens under the hood, read this.
You can't wake a person who is <b><i>pretending</i></b> to be asleep.<br />Like what <b>"it"</b> does not like - <i> Gurdjieff </i>
Hi, xxxx is of type A . So first it will check whether print() method is in class A before overriding the print method in class B. If its not present in A , it will give a compile error. The same thing happens here . Because print method in A is not visible to B , it assumes there is no print method in A and gives an error.
Completely agree with Shilpa. The JLS says that you cannot override a private method of a class.
When you declare another print() method in the child class, this print just happens to have the same name as a method in the parent class. It is NOT overriding the private method. Hence, the JVM will not dynamically pick the print() method of the child class at runtime.
And of course, the private print method is not visible to the child class, even through a reference to the parent. Hence, a compile-time error is thrown.
SCJP 5.0 | SCWCD 1.4 <br /> <br />If you don't know where you are going, any road will take you there!
First thanks for the reply... but let say i remove the private method in class A so it looks like this
when compiled and run it will print the value for "i", the question is -- isnt this the same as when the print method is private...? i mean, because when a method or variable that belongs to superclass is private the subclass doesnt see it, as if it doesnt exists. and the print method in Class B is simply just a method that belongs to class B... and not an override of the method in Class A.
[ August 16, 2006: Message edited by: Firman Drage CORRECT ME IF IM WRONG ]
i think the solution is... (looking back to the original code.. -see orginial thread) when the reference variable xxx is created its of a type A and at compile time, the xxx.print() will look for the print() method in class A, and since the print method in class A is private... it naturally say that it cannot find it... but let say, for argument sake, that the method A.print() is public.
At "compile time", xxx.print() sees that the method exist because its public -- also remember that is saying that xxx is a holder type A but its content is B -- so xxx.print() at "runtime" it will run the print() in B [ August 16, 2006: Message edited by: Firman Drage ]
Warning! Way too comfortable! Do not sit! Try reading this tiny ad instead:
Free, earth friendly heat - from the CodeRanch trailboss