Java declares a variable that implements an interface

This is my first question I ask here so that I can do something wrong.

I want to declare a variable that, as I know, refers to a class that implements the interface.

private <T extends Executable> T algorithm; 

It was my attempt to achieve the goal.

+4
source share
3 answers

You do not need to use generics for this. The following steps will be performed for any subclass / implementation of the executable:

 private Executable algorithm; 
+6
source

You cannot enter a type parameter in a field declaration. It should be the one introduced by the class itself.

eg.

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

Just declare it either as an interface, or a class that it sees that this class should implement the interface anyway. Depending on how you need it. but you need to specify instance variables like this.

 private YourInterfaceName variablename; private ClassName variablename; 

and then initiate them in the constructor.

Perhaps this tutorial will help you learn more about variables.

+3
source

Source: https://habr.com/ru/post/1486920/


All Articles