• Post Reply Bookmark Topic Watch Topic
  • New Topic

downcasting  RSS feed

 
Ranch Hand
Posts: 134
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
[Edit - fixed code tags and formatting - see UseCodeTags for details]

In the second comment(//2) i performed downcasting !clarify me how the reference 'd' is used to invoke both the methods of different classes
 
Bartender
Posts: 4568
9
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I'm not exactly sure what you're asking, but let's see if this helps...

On line 20 you create a Dwncast object, and assign it to a Base reference. You can do that safely because a Dwncast is-a Base.

On line 21 you then copy that reference to a Dwncast reference. You need an explicit cast here, because the compiler doesn't know that b is pointing to a Dwncast object. All it knows is that it's a Base. By adding the cast, you're effectively telling the compiler "trust me, it's really a Dwncast". The compiler takes your word for it, so lets you do it. You'll get a ClassCastException at run-time if it's not actually true.

After that, all that matters is that d is a Dwncast reference. And Dwncast objects have a fet() method (defined in the class) and a get() method (which it inherits from the Base class).

(Incidentally, is it not worth one more letter to have the more meaningful class name of Downcast?)
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!