Assign to a variable an object that extends a class and implements an Interface at the same time. I have a method like this
public static <T extends Component & MyInterface> T instance() {
if (test1) return new MyLabel();
if (test2) return new MyCombo();
if (test3) return new MyText();
}
class MyLabel extends JLabel implements MyInterface {
...
}
class MyCombo extends JComboBox implements MyInterface {
...
}
class MyText extends JTextField implements MyInterface {
...
}
this means the instance() returned object is a Component AND implements MyInterface. and I can do something like
instance.setEnable(true); // calling a Component method
instance.foo(); // calling a MyInterface method
Now I want to assign the returned value to a variable: how to declare the variable in order to bring with the variable all the Generics info?
I expect to be able to do something like this:
static <T extends Component & MyInterface> T myVar = instance();
myVar.setEnable(true); // calling a Component method
myVar.foo(); // calling a MyInterface method
and also this:
static void f1(Component c) {}
static void f2(MyInterface c) {}
f1(myVar);
f2(myVar);
In my opinion the question is different from the one in Why can't I use a type argument in a type parameter with multiple bounds? because I'm not using a type parameter inside a generic class declaration.