Win a copy of OCP Java SE 8 Programmer II Exam Study Guide this week in the OCP forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic

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

Posts: 3
  • Mark post as helpful
  • send pies
  • 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?
With a little knowledge, a cast iron skillet is non-stick and lasts a lifetime.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!