Bart Friederichs
Bart Friederichs

Reputation: 33531

Declare an attribute that both extends a class and implements an interface

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

Answers (2)

ther
ther

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

maress
maress

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

Related Questions