my dog learned polymorphism*
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Generics-compiler error Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login

Win a copy of Murach's Java Servlets and JSP this week in the Servlets forum!
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "Generics-compiler error" Watch "Generics-compiler error" New topic

Generics-compiler error

geet kaur
Ranch Hand

Joined: Sep 03, 2008
Posts: 78

Guitar and Violen extend Instrument even then its giving compiler error i dont understand this please help.....
Brij Garg
Ranch Hand

Joined: Apr 29, 2008
Posts: 234

List<? extends Instrument> list=new ArrayList<Instrument>();

with extends keyword we cannot add anything to list.

That is why compiler error is coming up.
M Srilatha
Ranch Hand

Joined: Aug 27, 2008
Posts: 137
When List<? extends Instrument> list is used, list can be assigned a collection that is a subtype of List and typed for <Instrument> or anything that extends Instrument.
And you cannot ADD anything into the collection.
If you try to add, then it will result in compiler error.

If you want to add elements to the collection, then you can use
List<? super Instrument> list.

Thanks,<br />Srilatha M
geet kaur
Ranch Hand

Joined: Sep 03, 2008
Posts: 78
ok but then whats the use of <? extends> when we cannot add anything to it??
Brij Garg
Ranch Hand

Joined: Apr 29, 2008
Posts: 234

List<Guitar> guitar = new ArrayList<Guitar>
List<Voilen> voilen = new ArrayList<Voilen>


public void test(list<? extends Instrument> list)
Instrument i= list.get(0);;

Now you can call test(guitar) and also test(voilen).

This is jut one example.
Sudarshan Chakrabarty
Ranch Hand

Joined: Apr 10, 2008
Posts: 38
<? extends XXX > is usually used as a parameter in a method signature.
For instance, the following method
public void printList(List<? extends Shape> shapes) {
can be passed a list of any objects which are extended from Shape.
If you have two classes which extends Shape
public class Square extends Shape{
// create List of Square objects
and public class Circle extends Shape{
// create List of Circle objects

You can pass a list of both Circle or Square objects to the printList() method as declared above.
Hope this makes sense

It is sorta covered in the JavaRanch Style Guide.
subject: Generics-compiler error
Similar Threads
mock exam question
Generics Issue
Generic Problem
Regarding Generics !
list interface