given a generic interface:
public interface I<E> {
public int interfaceMethod(E s);
}
and a generic class that implements the interface
public class A<T> implements I<T> {
private T val;
public A(T x) {
val = x;
}
public int interfaceMethod(T val) {
// looks like T should be of the same type as instance variable 'val'
return 0;
}
}
why does the following work?
public class Run {
public static void main(String[] args) {
A a = new A<String>("hello");
System.out.println(a.interfaceMethod(100)); \\ returns 0
}
}
I expected the T
type parameter of the method interfaceMethod
as defined in class A
to constrain the method to arguments that have the same type as that supplied to the constructor of A
. (in this case String
).
Why does a.interfaceMethod
not require an argument of type String
?
That happens because you ignored the warning "Raw use of parameter a" (or something like that)
Use:
A<String> a = new A<String>("hello");
When ignoring generic related warnings the code may compile when shouldn't.
This works because a
instance is typed to A
class only
You should type it like this:
A<String> a = new A<String>("hello");
If you wont specify the parameter, you will be able to put there all data types like String
, int
etc.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With