• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Generics-compiler error

 
geet kaur
Ranch Hand
Posts: 79
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

Guitar and Violen extend Instrument even then its giving compiler error i dont understand this please help.....
 
Brij Garg
Ranch Hand
Posts: 234
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

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
Posts: 137
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
geet kaur
Ranch Hand
Posts: 79
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
ok but then whats the use of <? extends> when we cannot add anything to it??
 
Brij Garg
Ranch Hand
Posts: 234
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

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

--------------------------------------------------

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

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

This is jut one example.
 
Sudarshan Chakrabarty
Ranch Hand
Posts: 38
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
<? 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

:roll:
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic