Extends and super difference - Generics Java 7

Asked

Viewed 74 times

1

I would like to know the difference of super e extends when declaring something Eneric in java, let’s go to the code that is easier.

class Pai { } 
class Filho extends Pai {   }
class Filha extends Pai {   }

public void main( String agss[] ) {

    //Qual a diferença entre < ? super Pai > e <Pai>
    List<? super Pai> a = new LinkedList<>();
    a.add( new Pai() );
    a.add( new Filho() );

    List<Pai> b = new LinkedList<>();
    b.add( new Pai() );
    b.add( new Filho() ); 


    //O que pode ser populado nesta lista?
    List<? extends Pai> c = new LinkedList<>();
    c.add( new Pai() ); //??
    c.add( new Filho() ); //? filho extends de pai 


    List<? extends Pai> d = new LinkedList<Filho>();//Pq isso compila se eu não posso popular a lista com filhos ?
    d.add( new Filho() ); 
}
  • What’s the difference between < ? super Pai > and <Pai> ?
  • What can be inserted into a List<? extends Pai> ?
    • Why does it compile if I can’t add one Filho the list ? List<? extends Pai> d = new LinkedList<Filho>()
  • Maybe this topic will answer your question: Why Polymorphism Doesn’t Work with Generics?

  • I had not seen this other question, perhaps it is more directed

  • The reply of the duplicate seems to answer perfectly this.

  • Reading the duplicate answer, I couldn’t understand the use of extends.

  • @Davidschrammel Read the first part, about covariance.

  • @Davidschrammel I voted to close the question because, although the other question is not equal, the answers there respond perfectly to what was asked here. At least it’s my understanding that if I were to answer this one I could just copy and paste. If you want to know something more about the subject, you can edit the question or create another one. Remember that questions can be reopened when appropriate.

  • @utluiz was able to understand the issues addressed in http://stackoverflow.com/questions/2723397/java-generics-what-is-pecs

Show 2 more comments
No answers

Browser other questions tagged

You are not signed in. Login or sign up in order to post.