有人可以向我解释为什么以下代码不起作用吗?
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();
}
}
我收到以下错误:
The method execute(capture#3-of ?) in the type Test.Strategy<capture#3-of ?>
is not applicable for the arguments (String)
我通过如下更改代码使其工作:
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");
}
}
但我想了解为什么原来的方法不起作用。