13_Review Lecture

Extends t s forthere is element in s pushspop

Info iconThis preview shows page 1. Sign up to view the full content.

View Full Document Right Arrow Icon
This is the end of the preview. Sign up to access the rest of the document.

Unformatted text preview: ehaves polymorphically –  “? extends” represent any sub types. –  “? super” represent any super types 20 Enforce Correct Type Parameters Instead of saying: Lunch<Meat, Starch, Soup>! ! We can say: Lunch<M extends Beef, S extends Noodle, C extends Cream>! Support Polymorphism Just like saying: Fruit f = new Apple();! f = new Orange();! ! We can say: Stack<? extends Fruit> sf = new Stack<Apple>();! sf = new Stack<Orange>();! Stack<? super Orange> sf = new Stack<Orange>();! sf = new Stack<Fruit>();! 21 Support Polymorphism Version 4 class Stack<T>{! public void pushAll(Stack<? super T> s){! for(//there is element in me)! s.push(pop());! }! public void popAll(Stack<? extends T> s) {! for(//there is element in s)! push(s.pop());! }! }! Stack<ClassA> s1 = new Stack<ClassA>();! Stack<ClassB> s2 = new Stack<ClassB>();! s2.pushAll(s1); ! s1.popAll(s2); ! 22 PECS Principle •  Producer Extends Consumer Super •  The parameter is a generic container P –  If you are going to go through the elements of P, P is a producer. –  If you are going to add things into P, P is a consumer •  Example: print(ArrayLis...
View Full Document

Ask a homework question - tutors are online