*
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes output Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Android Security Essentials Live Lessons this week in the Android forum!
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "output" Watch "output" New topic
Author

output

Raju Champaklal
Ranch Hand

Joined: Dec 10, 2009
Posts: 521


why does this print parent and not child? is this because the compiler decides which name to invoke according to the reference variable?

scjp 1.6 91%, preparing for scmad
"Time to get MAD now.. we will get even later"....by someone unknown
Roel De Nijs
Bartender

Joined: Jul 19, 2004
Posts: 5139
    
  12

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


SCJA, SCJP (1.4 | 5.0 | 6.0), SCJD
http://www.javaroe.be/
Ankit Garg
Sheriff

Joined: Aug 03, 2008
Posts: 9291
    
  17

A class' variables (instance variables) are not involved in polymorphism, that's why the output is "parent" and not "child"...


SCJP 6 | SCWCD 5 | Javaranch SCJP FAQ | SCWCD Links
sudipto shekhar
Ranch Hand

Joined: Apr 02, 2008
Posts: 818

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.


Regards, Sud.
SCJP 5 ScjpFAQ JLS
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: output
 
Similar Threads
Object from Subclass to Superclass
Help
Method Overlaoding questions/doubt
Question for variable initialization order
Polymorphism Problem