Can someone explain to me why the following code is not working?
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 get the following error:
The method execute(capture
I need this to work by changing the 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.
java generics bounded-wildcard
user191204
source share