Java generics, interfaces, and type restrictions

given the common interface:

public interface I<E> { public int interfaceMethod(E s); } 

and a general class that implements an 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 that the type parameter T the interfaceMethod method, as defined in class A , limits the method to arguments that are of the same type as constructor A (in this case String ).

Why does a.interfaceMethod not require an argument of type String ?

+5
source share
3 answers

While other answers explain that usually a compiler warning should appear. The explanation I was looking for was provided as a link to a previous post provided by @JB Nizet.

T t = new T<S>()

does not match

T<S> t = new T<S>()

The first example is a raw type . I was wondering why it works (that is ... if it compiles and does not throw an error at runtime), then this should be something.

The answers to this post are described in detail and explain why this is compiled (long story short, backward compatible). The post fully discloses and explains the implications for a system such as Java.

+1
source

This is because you ignored the warning "Unhandled using parameter a" (or something like that)

Using:

 A<String> a = new A<String>("hello"); 

By ignoring the general warnings that code can compile when not followed.

+1
source

This works because an instance of a is only injected into class a . You should enter it like this:

 A<String> a = new A<String>("hello"); 

If you do not specify a parameter, you can place all data types there, such as String , int , etc.

+1
source

All Articles