MattiasDC
MattiasDC

Reputation: 43

Java declaring a variable which implements an interface

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

Upvotes: 4

Views: 2519

Answers (3)

Akunosh
Akunosh

Reputation: 237

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.

Upvotes: 3

buritos
buritos

Reputation: 598

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

private Executable algorithm;

Upvotes: 6

Bhesh Gurung
Bhesh Gurung

Reputation: 51030

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;

Upvotes: 3

Related Questions