I would like to declare attribute that holds instance of class that implements 2 different interfaces. I have tried this syntax:
private <? extends Interface1 & Interface2> name;
and this:
private <T extends Interface1 & Interface2> T name;
None of those work. Is it possible? What’s the syntax? I’m trying to avoid declaring another interface that inherits from both Interface1 and Interface2.
Edit:
The class containing this attribute should not have any type arguments. That is nothing like this:
public class MyClass<T extends Interface1 & Interface2>{
private T name;
...
}
It would not make any sense for those using the class. It is not expected neither logical not possible for that class to be generic.
A variable cannot be generic.
is not possible – at which point is
Tdefined? When accessingvar, I cannot make much assumptions on what I used at assignment time.Java allows generics on classes and on methods. So you can have
and you can have a class-wide type
T.But always remember that in the end, it is implemented by type erasure. You can always emulate more complex logic using getters, setters and casts. When done properly, it will give you just as much type safety.
The simplest way to obtain a variable with the type safety you want is to just use two variables, and a setter to keep them in sync.
will of course give you a good type safety. But yes, it needs 4 bytes of additional memory, and a setter.
Here’s the casting approach you asked:
Note that in order to use
Tin the getter, we do need to have a parameter involving T.Assuming we know a class
Example implements Serializable, Cloneable, we can then use