



Study with the several resources on Docsity
Earn points by helping other students or get them with a premium plan
This page cannot be seen from the preview
Don't miss anything!




CMSC 330 2
CMSC 330 3
CMSC 330 4
CMSC 330 5
If for each object o1 of type S there is an object o2 of type T such that for all programs P defined in terms of T, the behavior of P is unchanged when o1 is substituted for o2 then S is a subtype of T.
CMSC 330 6
CMSC 330 7
class Stack { class Entry { Object elt; Entry next; Entry(Object i, Entry n) { elt = i; next = n; } } Entry theStack; void push(Object i) { theStack = new Entry(i, theStack); } Object pop() throws EmptyStackException { if (theStack == null) throw new EmptyStackException(); else { Object i = theStack.elt; theStack = theStack.next; return i; }}}
CMSC 330 8
Stack is = new Stack(); Integer i; is.push(new Integer(3)); is.push(new Integer(4)); i = (Integer) is.pop();
CMSC 330 9
CMSC 330 10
CMSC 330 11
class Stack
CMSC 330 12
Stack
CMSC 330 19
public static void reverseArray(Object [] A) { for(int i=0, j=A.length-1; i<j; i++,j--) { Object tmp = A[i]; A[i] = A[j]; A[j] = tmp; } }
CMSC 330 20
public class A { ... } public class B extends A { void newMethod(); } ... void foo(void) { B[] bs = new B[3]; A[] as;
as = bs; // Since B[] subtype of A[] as[0] = new A(); // (1) bs[0].newMethod(); // (2) Fails since not type B }
CMSC 330 21
int count(Collection
CMSC 330 22
CMSC 330 23
int count(Collection<?> c) { int j = 0; for (Iterator<?> i = c.iterator(); i.hasNext(); ) { Object e = i.next(); j++; } return j; }
CMSC 330 24
CMSC 330 25
int count(Collection<?> c) { int j = 0; for (Iterator<?> i = c.iterator(); i.hasNext(); ) { Object e = i.next(); c.add(e); // fails: Object is not? j++; } return j; }
CMSC 330 26
int count(Collection<?> c) { int j = 0; for (Object e : c) j++; return j; }
CMSC 330 27
void drawAll(Collection
void drawAll(Collection<?> c) { for (Shape s : c) s.draw(); }
// not allowed, assumes? is Shape CMSC 330 28
void drawAll(Collection<? extends Shape> c) { for (Shape s : c) s.draw(); }
CMSC 330 29
-? extends Shape actually gives an upper bound
CMSC 330 30
void foo(Collection<? extends Shape> c) { c.add(new Circle()); }