8 - CMPSCI 187: Programming With Data Structures Lecture 8:...

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

View Full Document Right Arrow Icon
CMPSCI 187: Programming With Data Structures Lecture 8: Polymorphism, Generics, and Exceptions 23 September 2011
Background image of page 1

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

View Full DocumentRight Arrow Icon
Polymorphism, Generics, and Exceptions • Object Polymorphism as in the Dog/Terrier Example • Method Polymorphism Through Supertypes • Why Not Always Use Object ? • Defning and Using Generic Types • Exceptions and How They Can be Dealt With • The Exceptions Class Hierarchy
Background image of page 2
Object Polymorphism: The Dog/Terrier Example • A polymorphic reference in Java code is a use of a variable in such a way the the behavior at run-time can depend on the actual class of the variable value. • In general polymorphism (“many shapes”) refers to any programming language concept that can deal with data of different kinds. • In our example where the Dog and Terrier classes each have their own bark ( ) method, any reference x.bark( ), where x is a Dog variable, is polymorphic because the method invoked depends on the class of x ’s value at run time.
Background image of page 3

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

View Full DocumentRight Arrow Icon
Method Polymorphism Through Supertypes • In an example where different kinds of Dogs bark in different ways, we can deFne a method in the Dog class that gets overridden as needed. This works because there is a single supertype of all the classes that need to bark. • So we can call the bark method from a Dog variable and the right method will run. • But this isn’t always satisfactory -- what if we had a method that was appropriate for some Dogs and not others, and the classes that were good for it did not form a single subclass of Dog. • We could deFne a dummy method in the Dog class, that caused an exception
Background image of page 4
Image of page 5
This is the end of the preview. Sign up to access the rest of the document.

Page1 / 10

8 - CMPSCI 187: Programming With Data Structures Lecture 8:...

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

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