This week's book giveaway is in the OCAJP forum. We're giving away four copies of OCA Java SE 8 Programmer I Study Guide 1Z0-808 and have Jeanne Boyarsky & Scott Selikoff on-line! See this thread for details.
C is correct. The code will compile without any error and also will not give any run time error. The variable p refers to the Child class object. The statement p.method2() on execution will first look for method2() in Child class. Since there is no method2() in child class, the method2() of Parent class will be invoked and thus "Parent's method2()" will be printed. Now from the method2() , there is a call to method1(). Please note that method1() of Parent class is private, because of which the same method (method1() of Parent class) will be invoked. Had this method(method1() of Parent class) been public/protected/friendly (default), Child's class method1() would be called. Thus C is correct answer. I don't understand why it matters whether the Parent's method is private or all of the above. [ Jess added UBB [code] tags to preserve whitespace, check 'em out! She also added a bit more descriptive title... ] [ March 11, 2003: Message edited by: Jessica Sant ]
A private method in a class is really just a 'helper method' - a way of organising the code efficiently within a class (maybe two or three methods within the class will want to use this method). It has no meaning outside an instance of this class as, being private, it may not be called from any instance of any other class (including subclasses). If method1() was not private in the superclass, it would be overriden in the subclass, so printing Child's method1() on execution. Hope this helps - Jon
Hello! In addition to Jon Entwistle's post... If parent's method1() was declared with a different access modifier, the child's method1() will result to as a valid override method. And in such case, the method belonging to the object type (in the example above is Child) will be invoked. Remember this rule: ** overload->refernece type (at compile time) ** override->object type (at runtime).
Originally posted by Jon Entwistle: If method1() was not private in the superclass, it would be overriden in the subclass, so printing Child's method1() on execution.
Just to state the same thing in a different way - private members are not inherited by subclasses. Therefore, the method is not overridden because the child class has no knowledge of the parent's method in the first place. I hope taht helps. Corey