• 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:
  • Tim Cooke
  • Campbell Ritchie
  • paul wheaton
  • Ron McLeod
  • Devaka Cooray
Sheriffs:
  • Jeanne Boyarsky
  • Liutauras Vilda
  • Paul Clapham
Saloon Keepers:
  • Tim Holloway
  • Carey Brown
  • Piet Souris
Bartenders:

upcasting - jtips exam

 
Ranch Hand
Posts: 229
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Hello everyone,
This is from jtips.net, mock exam no. 1

The output is:
sub.methodA() = 1
sup.methodA() = 0
sup1.methodA() = 10
I don't understand why process(sup1) leads to an output of zero.
sup1 is an object of Subclass, and x in Subclass is 1! I am obviously confused about the rules about upcasting. Can you help me?
 
Greenhorn
Posts: 26
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Let me try to explain.
When you pass sup1 to the function process(Superclass obj), it is actually a Superclass reference pointing to a Subclas object. The value of variable x is picked up on the basis of reference type(Superclass) and not on the what the reference is actually pointing to (sup1). Hence the value returned is value of x in Superclass i.e. 0.
bye
 
Rosie Vogel
Ranch Hand
Posts: 229
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Thank you Rana, I think I understand it now.
 
reply
    Bookmark Topic Watch Topic
  • New Topic