• 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
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

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
 
With a little knowledge, a cast iron skillet is non-stick and lasts a lifetime.
reply
    Bookmark Topic Watch Topic
  • New Topic