I stumbled across a Java casting situation involving Generics and Interfaces that I do not understand.
Please consider the following code where I create a List<Interface1>
. And then get()
an element and cast it to Interface2
without compiler error although these two interfaces are completely unrelated.
import java.util.*;
public class Main {
public static void main(String ... args) {
List<Interface1> list = new ArrayList<>();
list.add(new Interface1() {});
Interface1 ok = list.get(0);
Interface2 why = (Interface2)list.get(0);
}
}
interface Interface1 {
}
interface Interface2 {
}
Can anyone explain why there is not compiler error for the cast at the second get(0)
?
Two side notes: Executing the class throws a ClassCastException
(as expected). And using two classes instead of interfaces does actually generate compile errors.
The Java compiler won't let you cast a generic type across its type parameters because the target type, in general, is neither a subtype nor a supertype.
Implementing generics into your code can greatly improve its overall quality by preventing unprecedented runtime errors involving data types and typecasting.
Generics make a class, interface and, method, consider all (reference) types that are given dynamically as parameters. This ensures type safety. Generic class parameters are specified in angle brackets “<>” after the class name as of the instance variable. Generic constructors are the same as generic methods.
This behaviour is unrelated to generics: you can cast any interface to any other without compile errors.
You cannot do this with classes because Java can check at compile time whether one class can be casted to another.
With interfaces however the cast might succeed or fail, depending on the class that is actually implementing the interface. This can be discovered only at runtime though.
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