I just did this question myself and will tell you exactly what the system told me and it made sense to me.
When you call a method, it calls the method of the object type not the reference type. So, 'p' should look for 'method2' in class 'Child'. Now, since we know that there isn't any 'method2' in class 'Child', it will look for 'method2' in the superclass since superclass members are also accessible by the subclass object.
Now, if the 'method2' was private then I would say the compiler would give an error since subclass object can not see private members of its superclass.
this question highlights overriding rules....
hope it makes sense...
I am giving the exam on thursday and I can understand what everybody here is going through...
SCJP 1.4<br />SCWCD 1.4 ( next... )
Joined: Apr 06, 2005
Can you give more detail explaination on private access. I am still confused.
In your parent class you have two methods : method1() and method2() method1() is private(that means only members of that class can see it) method2() is public that means anybody and everybody in the program can se it and call it yuo can also see that method2() is calling method1() inside its body which is allowed due to the fact that both belong to same class . now in your child class you also have method1() that is not overriding parent method, because parent method is private, and child can not see or access it; so method1() in parent and method1() in child have nothing in common but the name and it is allowed in this situation. so when you create reference p which is type "Parent" and point it to object type "child" which is extending parent in this situation you are just calling a parents method2() since child does not have method2(). method2() is public and in turn calls method1(),and since method2() belongs to parent it will not look for method1() in child . this is how I think program handles this situation
For your second piece of code, a call to super() is inserted by the compiler into Mobile's constructor, which invokes Phone()'s constructor, hence the first line of output. Phone's constructor then invokes the overridden showDevice method in Mobile, since Mobile is the declared type vs a reference type of Phone.
However, String device in the mobile object is null until after its super classes constructor has finished running, so you get the following line of output: Mobile.showDevice,null.
Phone's constructor then completes and the rest of the program is executed straightforwardly. At least that's my take on it.
If you're having trouble following the execution of code like this, I find it useful to step through it using a debug tool, like in Eclipse or something similar.