Can someone explain to me why the following code does not work?
public class Test {
interface Strategy<T> {
void execute(T t);
}
public static class DefaultStrategy<T> implements Strategy<T> {
@Override
public void execute(T t) {}
}
public static class Client {
private Strategy<?> a;
public void setStrategy(Strategy<?> a) {
this.a = a;
}
private void run() {
a.execute("hello world");
}
}
public static void main(String[] args) {
Client client = new Client();
client.setStrategy(new DefaultStrategy<String>());
client.run();
}
}
I'm getting the following error:
The method execute(capture#3-of ?) in the type Test.Strategy<capture#3-of ?>
is not applicable for the arguments (String)
I've got it to work by altering code as follows:
public class Test {
interface Strategy<T> {
void execute(T t);
}
public static class DefaultStrategy<T> implements Strategy<T> {
@Override
public void execute(T t) {}
}
public static class Client<T> {
private Strategy<T> a;
public void setStrategy(Strategy<T> a) {
this.a = a;
}
private void run(T t) {
a.execute(t);
}
}
public static void main(String[] args) {
Client<String> client = new Client<String>();
client.setStrategy(new DefaultStrategy<String>());
client.run("hello world");
}
}
but I want to understand why the original approach did not work.