Unexpected type safety violation

A List<Item> could very well be an Item. See for example:

public class Foo extends Item implements List<Item> {
    // implement required methods
}

A cast tells the compiler: “I know you can’t be sure that this is a object of type Item, but I know better than you, so please compile”. The compiler will only refuse to compile that if it’s impossible for the returned object to be an instance of Item (like, for example, Integer can’t ever be a String)

At runtime, the type of the actual object returned by the method will be checked, and if it’s not actually an object of type Item, you’ll get a ClassCastException.

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)