The cast is technically possible. It cannot easily be proven by javac that it is not so in your case and the JLS actually defines this as a valid Java program, so flagging an error would be incorrect.
This is because List
is an interface. So you could have a subclass of a Date
that actually implements List
disguised as List
here - and then casting it to Date
would be perfectly ok. For example:
public class SneakyListDate extends Date implements List<Foo> {
...
}
And then:
List<Foo> list = new SneakyListDate();
Date date = (Date) list; // This one is valid, compiles and runs just fine
Detecting such a scenario might not always be possible, as it would require runtime information if the instance is coming from, for example, a method instead. And even if, it would require much more effort for the compiler. The compiler only prevents casts that are absolutely impossible due to there being no way for the class-tree to match at all. Which is not the case here, as seen.
Note that the JLS requires your code to be a valid Java program. In 5.1.6.1. Allowed Narrowing Reference Conversion it says:
A narrowing reference conversion exists from reference type S
to reference type T
if all of the following are true:
- [...]
- One of the following cases applies:
- [...]
S
is an interface type, T
is a class type, and T
does not name a final
class.
So even if the compiler could figure out that your case is actually provably impossible, it is not allowed to flag an error because the JLS defines it as valid Java program.
It would only be allowed to show a warning.
List
here.Date d = (Date) new Object();
– DecodestrList
was an instance of a class that implements List. – Alkalinity