How subtype can be added to a supertype list via Java Generics -
this question has answer here:
i trying compiles fine:
public interface training { public void train(); } public class javatraining implements training{ @override public void train() { // todo auto-generated method stub } } import java.util.*; public class testclass { /** * @param args */ public static void main(string[] args) { list<training> traininglist = new arraylist<training>(); traininglist.add(new javatraining()); for(training trainingitem : traininglist){ trainingitem.train(); } } }
this compiles fine , runs also.
but when try change main method below give compile time error.
why that?
import java.util.*; public class testclass { /** * @param args */ public static void main(string[] args) { list<training> traininglist = new arraylist<javatraining>(); } }
the compile time error is:
"type mismatch: cannot convert arraylist list"
i have read 1 post here. not clear doubt.
the question not duplicate of this since have not used anywhere
list<? extends training>
but still accepting objects of javatraining. how?
here why cannot this:
list<javatraining> jt = new arraylist<javatraining>(); // far list<training> traininglist = jt; // did; let's pretend compiles traininglist.add(new coboltraining()); // compiler must allow this, because `coboltraining` `training`.
the problem above lets put coboltraining
jt
, list of javatraining
.
Comments
Post a Comment