• 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

Overriding Q?

 
Ranch Hand
Posts: 34
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator


Answer is 4.
My Question is why not 1 also.
Since methods are called based on Object , why option1 is not correct?

Anyone Please explain
 
Ranch Hand
Posts: 51
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Answer 1 will not compile. The compiler checks that the method exist in the reference type, not the object type. At runtime, the JVM will dynamically bind the method that executes based on object type.

In this case, at compile time the compiler will confirm that every method called against variable 'a' is defined (at least abstract) in class Base. Attempting to call a.getFields() generates a compile error because getFields() is not defined in class Base.

It's easy in this case to see that variable 'a' will always contain an object of type Agg, but in more complex examples the compiler may not be able to confirm at compile-time the exact object type that the reference will contain...Hence, for safety sake, the compiler must complain.
 
Mark Patrick
Ranch Hand
Posts: 51
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
PS...You can always try to compile and run the example to see what it does....
 
Don't get me started about those stupid light bulbs.
reply
    Bookmark Topic Watch Topic
  • New Topic