Win a copy of Programmer's Guide to Java SE 8 Oracle Certified Associate (OCA) this week in the OCAJP forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Marcus Exam #3 Question 57

 
Dominic Mack
Greenhorn
Posts: 17
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
At first glance this answer seems wrong to me.

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?
 
Nain Hwu
Ranch Hand
Posts: 139
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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).]
 
Nain Hwu
Ranch Hand
Posts: 139
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Dominic,
Yes. 1 will be correct if you add getField() to Base class.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic