1 / 6

Généricité ?!

Généricité ?!. Conteneur générique. On a parler de conteneur générique Un Vector par exemple, typer par une classe Vector <T> v: est une liste d’objets (dérivés) de T Avec l’héritage class T extends U Vector <U> w = v; // interdit On peut déclarer un Vector de ? e xtends T

iren
Download Presentation

Généricité ?!

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. Généricité ?!

  2. Conteneur générique • On a parler de conteneur générique • Un Vector par exemple, typer par une classe • Vector<T> v: est une liste d’objets (dérivés) de T • Avec l’héritage class T extends U • Vector<U> w = v; // interdit • On peut déclarer un Vector de ? extends T • En lecture seule, pour le passage aux méthodes

  3. Généricité • Même syntaxe que pour les collections publicclass Pair<T> { private T first; private T second; public Pair(T first) { super(); this.first= first;} public T getFirst() {returnfirst;} publicvoidsetFirst(T first) {this.first= first;} //… } publicclass Main { publicstaticvoid main(String [] args){ Pair<Integer> t = new Pair<Integer>(10); t.setFirst(15); } }

  4. ? Wildcard encore • Pour l’instanciation (new) il faut bien spécifier le type : new Pair<MyClass> • Pas de new Pair<?> • Déclaration de type générique • Pair<?> p = new Pair<MyClass> • Après pour l’affectation c’est plus dur (il faut caster, faire attention) • Mais c’est parfait pour le paramètre d’une méthode

  5. ? extends super • ? : n’importe quoi • ? extendsMyClass : classes dérivées de • ? super MyClass : super classes de

  6. Exercice • Changer Pair pour avoir deux type différents • Syntaxe class name<T, S>

More Related