Reputation: 33531
I found this question: Member variable which must extend class A and implement some interface
and was wondering if there is a better way. Passing it as a parameter in a method works:
public <T extends Activity & IMyInterface> void start(T _callback) {
callback = _callback;
}
but how to correctly declare callback
as attribute? This:
Class<? extends Activity & IMyInterface> callback;
gives a syntax error.
Upvotes: 2
Views: 886
Reputation: 888
Problem is that T is not an instance of Class, you can declare it as:
Object callback;
MyType callback;
MyInterface callback;
Or you can define your class to be generic like this:
public class Example<T extends MyType & MyInterface>{
T callback
}
Upvotes: 1
Reputation: 3533
If you want to declare a variable that extends a class and implements an interface, you must declare the type variable on the class level, as based on this doc, you cannot declare the type variable on class attributes.
public class MyClass<T extends MyType & MyInterface>{
T extendsBothMyTypeAndInterface;
}
Upvotes: 1