4

this is my first question I ask here so I might do some things wrong.

I wish to declare a variable which I know is of a class which implements an interface.

private <T extends Executable> T algorithm;

This was my attempt to achieve the goal

0

3 Answers 3

6

You don't have to use generics for that. The following will work for any sub-class / implementation of Executable:

private Executable algorithm;
Sign up to request clarification or add additional context in comments.

Comments

3

You cannot introduce a type parameter in a field declaration. It has to be the one introduced by the class itself.

e.g.

 public class MyClass<T extends Executable> {
     private T algorithm;

3 Comments

Thanks, solved the problem. Would vote up, but I don't got 15 rep
But this also binds the class to that type. So, may be not the perfect solution. See the other solution, which should be more applicable here.
@RohitJain: You are right. But this is just to clear the doubt about declaring a field whose type is the type parameter.
3

Just declare it either as the interface or the class it is seeing that this class has to implement the interface anyway. Depending on how you need it. but you have to declasre instance variables like this.

private YourInterfaceName variablename;
private ClassName variablename;

and later initiate them in the constructor.

Maybe this toutorial helps you to learn more about variables.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.