What code placed after the comment //Here will result in calling the getFields method resulting in the output of the string "Agg"? 1) System.out.println(a.getFields()); 2) System.out.println(a.name); 3) System.out.println((Base) a.getFields()); 4) System.out.println( ((Agg) a).getFields());
The correct answer is 4. My question is this: Why, if I add the method getFields() to the Base class, does 1 also become a correct answer? I thought Java used dynamic method lookup to examine the actual object instance to find the correct method to invoke, not the declared type. Does it only use this when a method is being overriden?
Dominic, Dynamic lookup occurs during runtime. Before it can happen, the code needs to pass compilation. For case 1,2,3, they will fail compilation, because none of them are defined in the class Base. (see JLS 15.12) Case 4 will compile. At runtime, the dynamic lookup will pick up the correct method from class Agg (actually, dynamic lookup has not much left to do in this case - Agg has no subclass) [This message has been edited by Nain Hwu (edited October 03, 2001).] [This message has been edited by Nain Hwu (edited October 03, 2001).]
Joined: Sep 16, 2001
Dominic, Yes. 1 will be correct if you add getField() to Base class.