Java generics - Why “incompatible types” compilation error if a class' generic type doesn't exist in an invoked method? [duplicate]

让人想犯罪 __ 提交于 2019-12-04 15:52:35
A a = null;

should be:

A<String> a = null; // or better yet, new A<String>();

Although, you could substitute any class for String since, as you say, the T and O generics are different types.

Once you remove the generic parameter, you lose all the generics in your method call, which essentially becomes equivalent to calling:

Object method(Object t);

It's because Java's type erasure meaning for backward compatibility all generic type declarations exist only in source code and after compilation they are converted to Object references and proper casts behind the scenes so the JVM in this case is confused that you meant O or T.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!