Win a copy of Design for the Mind this week in the Design forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Downcasting and overridden methods

 
James Baud
Ranch Hand
Posts: 60
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

Can anyone explain why this prints 1 if f() is private in PolyB, else if public it prints 2?
------------------
~James Baud
He who asks, is a fool for five minutes;
but, he who does not ask, remains a fool forever. (Chinese proverb)
[This message has been edited by James Baud (edited April 10, 2001).]
 
Thomas Paul
mister krabs
Ranch Hand
Posts: 13974
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
PolyC can not override a private method in PolyB therefore f() is not eleigible for polymorphism.
 
Rebecca Pickett
Greenhorn
Posts: 15
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Originally posted by James Baud:
Can anyone explain why this prints 1 if f() is private in PolyB, else if public it prints 2?
[/B]

James, This is my take on it -- and I could be wrong. But it's a good basic OOP question.
ref1 is a reference to a PolyC object. ref2 is also a reference to the same PolyC object, but it's being cast to a PolyB. If PolyB.f() is private, that means that PolyC.f() does NOT override PolyB.f() with it's own code since private methods are only accessible inside that class. Thus, when PolyB.f() is private and you call PolyB.f() (however indirectly), it's going to print PolyB.f()'s code. When PolyB.f() is public, it is overridden by the PolyC.f() method when the PolyC object is created. I altered your code to print strings out, which helped me make more sense of it. Take a look:

Everyone, if I'm wrong, let me know!

 
Thomas Paul
mister krabs
Ranch Hand
Posts: 13974
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Here's the explanation:
private methods are also treated as final. Remember, final methods can not be overridden by a subclass so the compiler will always do compile time binding to the method. At compile time you are asking to run the f() method of PolyB. So since the f() method is private (and therefore final) it binds the execution to that method at compile time. At run time it does not matter what object ref2 is actually pointing to... the binding has already been done.
[This message has been edited by Thomas Paul (edited April 11, 2001).]
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic