How subtype can be added to a supertype list via Java Generics -


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

Popular posts from this blog

SPSS keyboard combination alters encoding -

Add new record to the table by click on the button in Microsoft Access -

javascript - jQuery .height() return 0 when visible but non-0 when hidden -