• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

Marcus Exam #3 Question 57

 
Greenhorn
Posts: 17
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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?
 
Ranch Hand
Posts: 139
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Dominic,
Yes. 1 will be correct if you add getField() to Base class.
 
With a little knowledge, a cast iron skillet is non-stick and lasts a lifetime.
reply
    Bookmark Topic Watch Topic
  • New Topic