inheritance - casting an ArrayList of generics in Java -


i have arraylist<? extends parent>. fill arraylist either child1, child2, etc...

then in main need access these particular child version. however, problem can

child1 c = (child1) arraylist.get(0)  

since downcasting. question how able this?

`package zoo;

import java.util.arraylist; import animal.animal;

public class zoo{ public arraylist animals;

  public zoo()   {       super();       }    public zoo(arraylist<? extends animals> animals)    {      animals = animals;   }   }  package animal;   public class animal {      public string name;      public animal(string name)     {         name = name;     }  }    package tiger;  import animal.animal;  public class tiger extends animal{ public int tailsize;  public tiger() {  } public tiger(int tailsize) {     tailsize = tailsize; } }  ### there chunk code of here takes in data , creates  zoo , fills animals of different types ###   tiger t = (tiger)zoo.animals.get(0); //yes index 0 tiger  system.out.println(t.tailsize); 

error exception in thread "main" java.lang.classcastexception: animal.animal cannot cast tiger.tiger


Comments

Popular posts from this blog

Is there a better way to structure post methods in Class Based Views -

performance - Why is XCHG reg, reg a 3 micro-op instruction on modern Intel architectures? -

jquery - Responsive Navbar with Sub Navbar -