2

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.

Community
  • 1
  • 1
Bart Friederichs
  • 33,050
  • 15
  • 95
  • 195
  • 2
    Shouldn't that be ``? You implement an interface, not extend it. – ThaMe90 May 02 '14 at 12:14
  • @ThaMe90 my thoughts as well, but according to this: http://stackoverflow.com/questions/10641584/method-argument-extends-class-implements-interface this is how it's done. – Bart Friederichs May 02 '14 at 12:16
  • Ha, I never knew that (I found the [doc](http://docs.oracle.com/javase/specs/jls/se7/html/jls-4.html#jls-4.4) that goes along with that). – ThaMe90 May 02 '14 at 12:19

2 Answers2

1

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;
}
maress
  • 3,533
  • 1
  • 19
  • 37
1

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
}
ther
  • 848
  • 8
  • 16