I have a basic question on method overriding. I have used 2 classes in different packages for illustrating this scenario.
Since the child is in a different package, the protected method hello() in child is not visible to the Parent. But when I run the program, the hello() method in child is getting executed. Does this means that, once a child class over rides the method, the child method would be always called irrespective of the access modifier?
The protected access modifier can be accessed by all classes in the same package as well as by the subclass,even if its in a different package.Moreover, in case of overridden methods, at runtime, the call to the method depends on the object type and not the refernce type.
So in this case, the parent reference variable has a reference type Parent and object type Child. So, it will invoke method in the Child class( as it is the object type). [ September 28, 2008: Message edited by: Abhi vijay ]
Hi Abi, Thanks for your prompt reply. The explanation you have given about the protected access modifier is absolutely right. That happens incase of inheritance. In my case,the main method is creating an object of child and referencing with the parent variable. The hello()method of child is not invoked by inheritance. Let me re-write the code to make it more readable. I am introducing a class called RunClass to create the Child object. The RunClass and Parent are in the same package and the Child is in a different package.
Just glance through the modified code. The RunClass and Parent are in the same package. So a call to the "protected parent.hello()" inside RunClass would be OK for the compiler. During runtime, the JVM sees that the parent reference variable is referencing a Child object, but the hello() method of the Child class should not be accessible to RunClass, which is in a different package. I think you got my point.
but [RunClass not extends Child ] ------------------------------ RunClass parent = new Child(); parent.hello(); --------------------------- in this case how it is running because hello() is in protected which is in Child Class ,different package .more over it is not extends Child .
please clarify my doubt. i think Abhi gives the explanation for overridding and protected access specifier...