• 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

Polymorphism

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

Hi everybody,

I have a doubt about this code.





The output is 5.

The source is Whizlabs SCJP5.0.

I would like to know why the output is 5 and not 6. Because I thought that in this code the polymorphism had been applied then the call c1.getObject() would return the object B.
Can anybody help me?
 
Ranch Hand
Posts: 53
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
It does return an object of type B. But instance variable call is resolved at compile time and at compile time the Object is of type A so x is 5.
 
Sheriff
Posts: 9707
43
Android Google Web Toolkit Hibernate IntelliJ IDE Spring Java
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Look at this thread...
 
Ranch Hand
Posts: 352
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Ok I see the thinking here, but isn't it the rule that instance variables cannot be overridden?

Certainly at compile time the compiler checks the reference type which is of the covariant type where the call to getObject returns an A: However, at runtime the JVM checks the Object type which is then a SubCovariantTest and thus the getObject returns an object of type B. However, as the SubCovariantTest instance variable x does not successfully override (as its an instance variable) the Superclass x value is still used and hence 5 is returned?
 
You ridiculous clown, did you think you could get away with it? This is my favorite tiny ad!
a bit of art, as a gift, the permaculture playing cards
https://gardener-gift.com
reply
    Bookmark Topic Watch Topic
  • New Topic