The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Polymorphism Confusion Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "Polymorphism Confusion" Watch "Polymorphism Confusion" New topic

Polymorphism Confusion

Ronan Kearney

Joined: May 08, 2009
Posts: 2
Heres a program I wrote which I am having trouble understanding

The output is:

superRef: 1
sub methodX
subRef: 2
sub methodX

If the runtime type of the object is SubClass in both cases, then why when printing i, does the reference to i resolve to the SuperClass in the first case and the SubClass in the second case. Does the reference variable have some influence as it is different in both cases?

The call to methodX resolves to the SubClass in both cases as I would expect from polymorphism behavior
Ruben Soto
Ranch Hand

Joined: Dec 16, 2008
Posts: 1032
Welcome to the ranch, Ronan.

Polymorphism only involves instance methods. For everything else (static variables, instance variables, static methods) the only thing that matters is the type of the reference, not the type of the actual object.

All code in my posts, unless a source is explicitly mentioned, is my own.
I agree. Here's the link:
subject: Polymorphism Confusion
It's not a secret anymore!