Win a copy of Getting started with Java on the Raspberry Pi this week in the Raspberry Pi forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Ron McLeod
  • Paul Clapham
  • Tim Cooke
  • Jeanne Boyarsky
Sheriffs:
  • Rob Spoor
  • Devaka Cooray
  • Liutauras Vilda
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Tim Moores
  • Mikalai Zaikin
Bartenders:
  • Piet Souris

Sub class method call using interface reference.

 
Ranch Hand
Posts: 94
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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??
 
Bartender
Posts: 4568
9
  • Likes 1
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Thanks
 
If you believe you can tell me what to think, I believe I can tell you where to go. Go read this tiny ad!
Low Tech Laboratory
https://www.kickstarter.com/projects/paulwheaton/low-tech-0
reply
    Bookmark Topic Watch Topic
  • New Topic