lec17 Subtype vs. Parametric Polymorphism Generics

lec17 Subtype vs. Parametric Polymorphism Generics -...

Info iconThis preview shows pages 1–2. Sign up to view the full content.

View Full Document Right Arrow Icon
Subtype vs. Parametric Polymorphism: Generics ============================================= (notes by Todd Millstein, UCLA) As we saw previously, the point of subtyping is to give us a sort of Polymorphism. Recall the function: void ScreenSaver(Point p){ ... } This could take as input any object whose type was a subtype of Point -- thereby allowing us to build screensaver using ColorPoint, TextPoint, ColorTextPoint etc. objects. Thus, the function ScreenSaver is also polymorphic -- in that it allows different kinds of inputs, not one fixed type. This is known as subtype polymorphism. As Java has subtype polymorphism, it would seem that this subsumes ML-style ``parametric" polymorphism. Where ML would use 'a, we'll use Object, allowing any object to be passed. Works sometimes, but can't always do what parametric polymorphism does. interface List { void add(Object o); Object get(int i); } List lst = . ..; lst.add("hello"); ... String s = lst.get(0); // type error! Problem: get returns an Object -- can't guarantee that it is a String. In Java 1.4 and earlier, the only option is to put a cast: String s = (String) lst.get(0); This tells the typechecker: "trust me, I know the first element of the list is a String". Not checked until run time. E.g.
Background image of page 1

Info iconThis preview has intentionally blurred sections. Sign up to view the full version.

View Full DocumentRight Arrow Icon
Image of page 2
This is the end of the preview. Sign up to access the rest of the document.

This note was uploaded on 02/14/2008 for the course CSE 130 taught by Professor Jhala during the Fall '06 term at UCSD.

Page1 / 4

lec17 Subtype vs. Parametric Polymorphism Generics -...

This preview shows document pages 1 - 2. Sign up to view the full document.

View Full Document Right Arrow Icon
Ask a homework question - tutors are online