This week's book giveaway is in the OCAJP forum.
We're giving away four copies of Programmer's Guide to Java SE 8 Oracle Certified Associate (OCA) and have Khalid A Mughal & Rolf W Rasmussen on-line!
See this thread for details.
Win a copy of Programmer's Guide to Java SE 8 Oracle Certified Associate (OCA) this week in the OCAJP 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: 10386
132
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: 9527
32
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