• 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

How to call a generic method with two bounds (for a single argument) if one bound needs a cast

 
Greenhorn
Posts: 3
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
I want to specify two types for a method's formal parameter. That's still simple: Make it a generic method with a type parameter like <T extends MyClass & MyInterface>.

Calling that method having an expression of type MySubClass (which extends MyClass and implements MyInterface) works fine.

But how can i call the method if i have an expression of (compile-time) type MyClass which i know is also of type MyInterface? If i cast to MyInterface, the compiler does not treat it as type "MyClass & MyInterface" (like it should?), but only MyInterface.

Here's the broken code:


I want method f to work for all MyClass subclasses which implement MyInterface, so i don't want to simply declare: void f(MySubClass o).

The only solution i can think of is using an extra adapter class like this:

and change callF1 and callF2 to


Is there a better way to fix methods callF1 and callF2?
Thanks!
 
Consider Paul's rocket mass heater.
reply
    Bookmark Topic Watch Topic
  • New Topic