Win a copy of Re-engineering Legacy Software this week in the Refactoring forum
or Docker in Action in the Cloud/Virtualization forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

inner classes help

 
Joanne Fire
Ranch Hand
Posts: 33
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hello, I was just wondering if someone can help me understand inner classes a little. If I have the following code:

If we execute the following lines on the code
Child myChild = new Child();
Parent myParent = new Parent();
myChild.writeIt();
myParent.writeIt();
myChild.displayIt();
myParent.displayIt();
Why does the following code display?
I am child
I am child
I am parent
I am parent

==
Thanks!

(Marilyn added code tags for better readability)
[This message has been edited by Marilyn deQueiroz (edited November 23, 2001).]
 
Marilyn de Queiroz
Sheriff
Posts: 9059
12
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hmmm. I get
I am child
I am parent
I am parent
I am parent

This question seems to have more to do with overriding than with inner classes. writeIt() in class Child overrides writeIt() in class Parent and is used when it is called by a Child object. Child has no method displayIt(), so of course you get the Parent version.
 
Joanne Fire
Ranch Hand
Posts: 33
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Sorry Marilyn! I posted the wrong code for the objects, it should be:
Child myChild = new Child();
Parent myParent = myChild;
instead of:
Child myChild = new Child();
Parent myParent = new Parent();
but still I don't FULLY understand how it all works together.
Thanks for your prompt response!
.. Joanne

Originally posted by Marilyn deQueiroz:
Hmmm. I get
I am child
I am parent
I am parent
I am parent

This question seems to have more to do with overriding than with inner classes. writeIt() in class Child overrides writeIt() in class Parent and is used when it is called by a Child object. Child has no method displayIt(), so of course you get the Parent version.

 
Marilyn de Queiroz
Sheriff
Posts: 9059
12
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Ok. Now my results match yours, but the reason is still the same. writeIt() in class Child overrides writeIt() in class Parent and is used when it is called by a Child object even when the Child object has a Parent reference. Child has no method displayIt(), so you get the Parent version. Have you read How my Dog learned Polymorphism yet? It might help you understand what's happening here.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic