This week's book giveaway is in the Performance forum.
We're giving away four copies of The Java Performance Companion and have Charlie Hunt, Monica Beckwith, Poonam Parhar, & Bengt Rutisson on-line!
See this thread for details.
Win a copy of The Java Performance Companion this week in the Performance forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

output

 
Raju Champaklal
Ranch Hand
Posts: 521
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator


why does this print parent and not child? is this because the compiler decides which name to invoke according to the reference variable?
 
Roel De Nijs
Sheriff
Posts: 10230
129
AngularJS Chrome Eclipse IDE Hibernate Java jQuery MySQL Database Spring Tomcat Server
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
is this because the compiler decides which name to invoke according to the reference variable?
No, because if you changed it to a reference variable of type Child you still get "parent" as output. I don't know what this example has to prove, because you are not overriding, overloading,... You just declared 2 different variables (with the same name = shadowing).
So your example is completely similar to this one:
You have to override the say-method in the Child class and add something like this:Both will print.
Kind regards,
Roel
 
Ankit Garg
Sheriff
Posts: 9521
22
Android Google Web Toolkit Hibernate IntelliJ IDE Java Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
A class' variables (instance variables) are not involved in polymorphism, that's why the output is "parent" and not "child"...
 
sudipto shekhar
Ranch Hand
Posts: 826
Chrome Eclipse IDE Oracle
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Ankit Garg wrote:A class' variables (instance variables) are not involved in polymorphism, that's why the output is "parent" and not "child"...


Yes, the exact answer. To be more specific, instance variables are not overridden.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic