aspose file tools*
The moose likes Beginning Java and the fly likes inner classes help Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Soft Skills this week in the Jobs Discussion forum!
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "inner classes help" Watch "inner classes help" New topic
Author

inner classes help

Joanne Fire
Ranch Hand

Joined: Nov 22, 2001
Posts: 33
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

Joined: Jul 22, 2000
Posts: 9053
    
  12
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.

JavaBeginnersFaq
"Yesterday is history, tomorrow is a mystery, and today is a gift; that's why they call it the present." Eleanor Roosevelt
Joanne Fire
Ranch Hand

Joined: Nov 22, 2001
Posts: 33
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

Joined: Jul 22, 2000
Posts: 9053
    
  12
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.
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: inner classes help