Why a general list can be passed to its type parameter

Why is the following code compiling?
Why is it allowed to cast a general list to its type parameter if the parameter is an interface but not a super-interface in general?

What does it mean?

//Connection can be substituted by any interface
List<Connection> list = null;
Connection c = (Connection) list; 
+3
source share
3 answers

This has nothing to do with the type parameter. This also works:

List<String> list = null;
Connection c = (Connection) list; 

Perhaps because List- this is the type of interface. It would be possible for the list link to contain an object that implements the interface List, as well as Connection(whatever, class or interface) the cast works for.

, , . , , .. :

    JComponent c = null;
    ArrayList l = (ArrayList) c;

, Java Language - 30 .

+12

, .

- , , - . -, .

0

, . . (, List to String), - , . ,

if(a instanceof bClass){
    ((bClass)a).doSomething(...);
}
0
source

Source: https://habr.com/ru/post/1770907/


All Articles