Ok, so here is my problem:
I have a list containing interfaces - List
- and a list of interfaces that extend that interface: Li
This works :
public class TestList {
interface Record {}
interface SubRecord extends Record {}
public static void main(String[] args) {
List extends Record> l = new ArrayList();
List l2 = new ArrayList();
Record i = new Record(){};
SubRecord j = new SubRecord(){};
l = l2;
Record a = l.get( 0 );
((List)l).add( i ); //<--will fail at run time,see below
((List)l).add( j ); //<--will be ok at run time
}
}
I mean it compiles, but you will have to cast your List extends Record>
before adding anything inside. Java will allow casting if the type you want to cast to is a subclass of Record
, but it can't guess which type it will be, you have to specify it.
A List
can only contain Records
(including subRecords
), A List
can only contain SubRecords
.
But A List
List
has it cannot contains Records
, and subclasses should always do what super classes can do. This is important as inheritance is specilisation, if List
would be a subclass of List
, it should be able to contain ` but it'S not.
A List
and a List
both are List extends Record>
. But in a List extends Record>
you can't add anything as java can't know which exact type the List
is a container of. Imagine you could, then you could have the following statements :
List extends Record> l = l2;
l.add( new Record() );
As we just saw, this is only possible for List
not for any List
such as List
.
Regards, Stéphane