This is a question from J@whiz. The answer is that it prints Parent's method2() Parent's method1() p is an instance of Child with a reference of a Parent. Method2 is inherited from Parent and is invoked for p.method2(). But,I expected to see Child's method1 in the output. I understand that method1() is overridden to be more accessible( private in Parent and public in Child) and should be invoked here.
Someone please explain what is happening. I referred the JLS (126.96.36.199) for method invocation and in its terms the target object/reference here is Child. So, I guess Childs method1 should have been invoked.
Originally posted by Basant K Sahu: I understand that method1() is overridden to be more accessible...
Oops! That's your mistake. method1 is NOT overridden. Private methods are not inherited and, therefore, can not be overridden. Try changing method1 to protected in the Parent class instead of private and you'll see what you expected. I hope that helps, Corey [ July 26, 2002: Message edited by: Corey McGlone ]
An instance method that is inherited from a super class can be overridden by a method declared with the same signature in the sub class. A static method that is inherited from a super class can be hidden by a static method declared with the same signature in the sub class. However, a private method is not inherited. A method declared in the subclass that has the same name as a private method in the super class does not override or hide the super class method because the super class method was not exposed as part of the external API of the super class. A sub class method that overrides or hides an inherited super class method must have the same return type as the super class method. Also, the overriding or hiding method of the subclass can not throw any additional checked exceptions. However, a sub class method that has the same signature as a private super class method is free to declare any return type or any "throws" clause. To convince yourself that a private method is not inherited, go ahead and change the return type of the sub class method. You will find that the program still compiles.
Dan Chisholm<br />SCJP 1.4<br /> <br /><a href="http://www.danchisholm.net/" target="_blank" rel="nofollow">Try my mock exam.</a>