{[ promptMessage ]}

Bookmark it

{[ promptMessage ]}

lec17 Subtype vs. Parametric Polymorphism Generics

lec17 Subtype vs. Parametric Polymorphism Generics -...

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

View Full Document Right Arrow Icon
http://www.cs.ucsd.edu/classes/fa06/cse130/lectures/lec17.txt 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.
Image of page 1

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

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

{[ snackBarMessage ]}

What students are saying

  • Left Quote Icon

    As a current student on this bumpy collegiate pathway, I stumbled upon Course Hero, where I can find study resources for nearly all my courses, get online help from tutors 24/7, and even share my old projects, papers, and lecture notes with other students.

    Student Picture

    Kiran Temple University Fox School of Business ‘17, Course Hero Intern

  • Left Quote Icon

    I cannot even describe how much Course Hero helped me this summer. It’s truly become something I can always rely on and help me. In the end, I was not only able to survive summer classes, but I was able to thrive thanks to Course Hero.

    Student Picture

    Dana University of Pennsylvania ‘17, Course Hero Intern

  • Left Quote Icon

    The ability to access any university’s resources through Course Hero proved invaluable in my case. I was behind on Tulane coursework and actually used UCLA’s materials to help me move forward and get everything together on time.

    Student Picture

    Jill Tulane University ‘16, Course Hero Intern