Win a copy of Kotlin in Action this week in the Kotlin forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic

Polymorphism Confusion  RSS feed

 
Ronan Kearney
Greenhorn
Posts: 2
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 1032
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
It is sorta covered in the JavaRanch Style Guide.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!