As I know, one of the main purposes of generics in Java is providing compile-time type safety. If it gets compiled, the code will run without issues.
Then why is the following code being compiled?
public static void main(String[] args) {
String s = getList();
}
private static <T extends List> T getList() {
return (T)new ArrayList();
}
It compiles fine. Where is my type-safe compilation? The getList()
method has nothing in common with the String
class.
MyClass extends String implements List
could be possible at compile time as the compiler doesn't consider String beingfinal
, as you said, for those kind of generic-checks. – Ommatidium