0

Possible Duplicate:
Implementations and Collections

My super class is Exam. One of my sub classes is Analytical.

This is a valid within my ide

Exam object = new Analytical();

However this is not.

ArrayList<Exam> object = new ArrayList<Analytical>();

The error is from new to the end of the statement and it says "Change type of object to ArrayList. So my question is how can I properly utilize polymorphis with this data structure. Thank you.

Community
  • 1
  • 1
gmustudent
  • 2,229
  • 6
  • 31
  • 43
  • 5
    http://stackoverflow.com/questions/7098402/implementations-and-collections/ – zw324 Oct 01 '12 at 17:42
  • [Also worth looking at](http://stackoverflow.com/questions/12604477/use-of-in-collection-generics/12605337#12605337) – Brian Oct 01 '12 at 20:56

3 Answers3

1

You cannot have different parameterized types on two sides of generic type declaration..

So, you must use the same type on both side..

It should be: -

ArrayList<? extends Exam> object = new ArrayList<Analytical>();

or

ArrayList<Exam> object = new ArrayList<Exam>();

or

ArrayList<? extends Exam> object = new ArrayList<Exam>();

Polymorphism, does not apply on the parameterized type..

Rohit Jain
  • 209,639
  • 45
  • 409
  • 525
0

You need to change it to something like:

ArrayList<? extends Exam> object = new ArrayList<Exam>();

Inheritance in generics is little different from our regular understanding.

kosa
  • 65,990
  • 13
  • 130
  • 167
  • 1
    Or `ArrayList extends Exam> object = new ArrayList();` – Gilberto Torrezan Oct 01 '12 at 17:43
  • Question. How will java know that I want the object type to be the Analytical subclass and not the MultipleChoice subclass for example. In other words, how can I specify the object type I desire. – gmustudent Oct 01 '12 at 17:48
  • 1
    If you want to keep only Analytical, not another type, then ArrayList object = new ArrayList(); – kosa Oct 01 '12 at 17:49
0

Collections are checked only during Compilation time not during the Runtime, so this measure has been taken, so that by mistake a wrong type doesn't get into the collection...

ArrayList<? extends Exam> object = new ArrayList<Analytical>();

or

ArrayList<? extends Exam> object = new ArrayList<Exam>();

Kumar Vivek Mitra
  • 33,294
  • 6
  • 48
  • 75