• Post Reply Bookmark Topic Watch Topic
  • New Topic

Sub class method call using interface reference.  RSS feed

 
john sal
Ranch Hand
Posts: 94
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator


Now from the main method of class MainClass I want to call methodA() of class Example. One approach of doing the same is as follows

((Example)intf).methodA();

Can somebody let me know if such kind of method call be should avoided in java or is it alwayz fine to call a method this way?? If not then why and what should be the correct approach??
 
Matthew Brown
Bartender
Posts: 4568
9
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
It's OK to do it if you can guarantee it will work. If there's any chance that intf is pointing to an instance of another class, you should check first (using instanceof).

However, while casting is sometimes necessary, it can be an indication that the design is flawed. In the particular example you've given, if you want to treat the object as an Example, then assign it to an Example reference variable in the first place. In a more realistic example, there may well be a better way but it's impossible to say what that would be without knowing more about it.
 
john sal
Ranch Hand
Posts: 94
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks
 
Don't get me started about those stupid light bulbs.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!