CMSC 330: Organization of Programming Languages Polymorphism.

Slides:



Advertisements
Similar presentations
1 Exceptions: An OO Way for Handling Errors Rajkumar Buyya Grid Computing and Distributed Systems (GRIDS) Laboratory Dept. of Computer Science and Software.
Advertisements

Exceptions CSE301 University of Sunderland Harry Erwin, PhD.
Topics Introduction Types of Errors Exceptions Exception Handling
Exception Handling Chapter 15 2 What You Will Learn Use try, throw, catch to watch for indicate exceptions handle How to process exceptions and failures.
C++ Programming: Program Design Including Data Structures, Fourth Edition Chapter 15: Exception Handling.
COMP 121 Week 5: Exceptions and Exception Handling.
CMSC 330: Organization of Programming Languages Exceptions.
Chapter 16: Exception Handling C++ Programming: From Problem Analysis to Program Design, Fifth Edition.
Exceptions and Exception Handling Carl Alphonce CSE116 March 9, 2007.
Exceptions1 Syntax, semantics, and pragmatics. Exceptions2 Syntax, semantics, pragmatics Syntax –How it looks, i.e. how we have to program to satisfy.
Exception Handling1. 2 Exceptions  Definition  Exception types  Exception Hierarchy  Catching exceptions  Throwing exceptions  Defining exceptions.
Exception Handling Chapter 12.  Errors- the various bugs, blunders, typos and other problems that stop a program from running successfully  Natural.
Exceptions and Exception Handling Carl Alphonce CSE116.
Exceptions1 Syntax, semantics, and pragmatics. Exceptions2 Syntax, semantics, pragmatics Syntax –How it looks, i.e. how we have to program to satisfy.
CSI 3120, Exception handling, page 1 Exception and Event Handling Credits Robert W. Sebesta, Concepts of Programming Languages, 8 th ed., 2007 Dr. Nathalie.
Java Generics.
11-Jun-15 Exceptions. 2 Errors and Exceptions An error is a bug in your program dividing by zero going outside the bounds of an array trying to use a.
16-Jun-15 Exceptions. Errors and Exceptions An error is a bug in your program dividing by zero going outside the bounds of an array trying to use a null.
Java Generics. 2 The Dark Ages: Before Java 5 Java relied only on inclusion polymorphism  A polymorphism code = Using a common superclass Every class.
Exceptions in Java Fawzi Emad Chau-Wen Tseng Department of Computer Science University of Maryland, College Park.
Exceptions. Errors and Exceptions An error is a bug in your program –dividing by zero –going outside the bounds of an array –trying to use a null reference.
06 - Exceptions. 2 ©S. Uchitel, 2004 A familiar sight? Bluescreen.scr.
1 Generics and Using a Collection Generics / Parameterized Classes Using a Collection Customizing a Collection using Inheritance Inner Classes Use of Exceptions.
12.1 Exceptions The limitations of traditional methods of exception handling Error conditions are a certainty in programming Programmers make.
1 Exception and Event Handling (Based on:Concepts of Programming Languages, 8 th edition, by Robert W. Sebesta, 2007)
Exceptions. Many problems in code are handled when the code is compiled, but not all Some are impossible to catch before the program is run  Must run.
June 14, 2001Exception Handling in Java1 Richard S. Huntrods June 14, 2001 University of Calgary.
Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved Chapter 18 Exception Handling.
Object Oriented Programming
Chapter 12: Exception Handling
Slides Credit Umair Javed LUMS Web Application Development.
Chapter 21 Generics 1. Generics - Overview Generic Methods specify a set of related methods Generic classes specify a set of related types Software reuse.
07 Coding Conventions. 2 Demonstrate Developing Local Variables Describe Separating Public and Private Members during Declaration Explore Using System.exit.
Effective Java: Generics Last Updated: Spring 2009.
Generics1 Parametrized classes and methods. Generics2 What are generics Generics are classes or interfaces that can be instantiated with a variety of.
Generics1 Parametrized classes and methods. Generics2 What are generics Generics are classes or interfaces that can be instantiated with a variety of.
1 Generics and Using a Collection Generics / Parameterized Classes Using a Collection Customizing a Collection using Inheritance Inner Classes Use of Exceptions.
Copyright © 2002, Systems and Computer Engineering, Carleton University a-JavaReview.ppt * Object-Oriented Software Development Unit.
Java 5 Part 1 CSE301 University of Sunderland Harry Erwin, PhD.
Exceptions in Java. Exceptions An exception is an object describing an unusual or erroneous situation Exceptions are thrown by a program, and may be caught.
Chapter 3 Inheritance and Polymorphism Goals: 1.Superclasses and subclasses 2.Inheritance Hierarchy 3.Polymorphism 4.Type Compatibility 5.Abstract Classes.
Exceptions, cont’d. Factory Design Pattern COMP 401 Fall 2014 Lecture 12 9/30/2014.
CMSC 330: Organization of Programming Languages Java Generics.
Exceptions and Assertions Chapter 15 – CSCI 1302.
©SoftMoore ConsultingSlide 1 Generics “Generics constitute the most significant change in the Java programming language since the 1.0 release.” – Cay Horstmann.
 In the java programming language, a keyword is one of 50 reserved words which have a predefined meaning in the language; because of this,
Exception Handling in Java Topics: Introduction Errors and Error handling Exceptions Types of Exceptions Coding Exceptions Summary.
SOEN 343 Software Design Section H Fall 2006 Dr Greg Butler
Chapter 15: Exception Handling C++ Programming: Program Design Including Data Structures, Fifth Edition.
CS212: Object Oriented Analysis and Design Lecture 19: Exception Handling.
Copyright © Curt Hill Error Handling in Java Throwing and catching exceptions.
Programming & Debugging. Key Programming Issues Modularity Modifiability Ease of Use Fail-safe programming Style Debugging.
1 Exceptions. 2 Syntax Errors, Runtime Errors, and Logic Errors syntax errors, runtime errors, and logic errors You learned that there are three categories.
Java How to Program, 9/e © Copyright by Pearson Education, Inc. All Rights Reserved.
(c) University of Washington10-1 CSC 143 Java Errors and Exceptions Reading: Ch. 15.
Exceptions Lecture 11 COMP 401, Fall /25/2014.
And other languages…. must remember to check return value OR, must pass label/exception handler to every function Caller Function return status Caller.
1 Chapter 21 Generics. 2 Objectives F To use generic classes and interfaces (§21.2). F To declare generic classes and interfaces (§21.3). F To understand.
Throw, Throws & Try-Catch Statements Explanations and Pictures from: Reference:
(C) 2010 Pearson Education, Inc. All rights reserved. Java How to Program, 8/e.
Introduction to Exceptions in Java CS201, SW Development Methods.
Design issues for Object-Oriented Languages
Generics, Exceptions and Undo Command
Chapter 20 Generic Classes and Methods
Exceptions 10-Nov-18.
Part B – Structured Exception Handling
CSE 143 Java Exceptions 1/18/2019.
Exceptions 10-May-19.
Chapter 19 Generics.
Exception Handling.
Presentation transcript:

CMSC 330: Organization of Programming Languages Polymorphism

CMSC 3302 An Integer Stack Implementation class Stack { class Entry { Integer elt; Entry next; Entry(Integer i, Entry n) { elt = i; next = n; } } Entry theStack; void push(Integer i) { theStack = new Entry(i, theStack); } Integer pop() throws EmptyStackException { if (theStack == null) throw new EmptyStackException(); else { Integer i = theStack.elt; theStack = theStack.next; return i; }}}

CMSC 3303 Integer Stack Client Stack is = new Stack(); Integer i; is.push(new Integer(3)); is.push(new Integer(4)); i = is.pop(); Now we want a stack of Floats … or some objects …

CMSC 3304 Polymorphism Using Object 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 3305 New Stack Client Stack is = new Stack(); Integer i; is.push(new Integer(3)); is.push(new Integer(4)); i = (Integer) is.pop(); Now Stacks are reusable –push() works the same –But now pop() returns an Object Have to downcast back to Integer Not checked until run-time

Polymorphism From the Greek... –πολοί: “poloi” = “many” –μορφή: “morphi” = “form” Polymorphism refers to the concept of taking on different forms –Data representing multiple concepts –Code operating on multiple input types CMSC 330

7 Polymorphism Subtyping is a kind of polymorphism –Sometimes called subtype polymorphism –Allows method to accept objects of many types We saw parametric polymorphism in OCaml –It’s polymorphism because polymorphic functions can be applied to many different types Ad-hoc polymorphism is overloading –Operator overloading in C++ –Method overloading in Java

CMSC 3308 Parametric Polymorphism (for Classes) After Java 1.5, we can parameterize the Stack class by its element type Syntax: –Class declaration:class A {... } A is the class name, as before T is a type variable, can be used in body of class (...) –Client usage declaration: A x; We instantiate A with the Integer type

CMSC 3309 class Stack { class Entry { ElementType elt; Entry next; Entry(ElementType i, Entry n) { elt = i; next = n; } } Entry theStack; void push(ElementType i) { theStack = new Entry(i, theStack); } ElementType pop() throws EmptyStackException { if (theStack == null) throw new EmptyStackException(); else { ElementType i = theStack.elt; theStack = theStack.next; return i; }}} Parametric Polymorphism for Stack

CMSC Stack Client Stack is = new Stack (); Integer i; is.push(new Integer(3)); is.push(new Integer(4)); i = is.pop(); No downcasts Type-checked at compile time No need to duplicate Stack code for every usage –line i = is.pop(); can stay the same even if the type of is isn’t an integer in every path through the program

CMSC Parametric Polymorphism for Methods String is a subtype of Object 1.static Object id(Object x) { return x; } 2.static Object id(String x) { return x; } 3.static String id(Object x) { return x; } 4.static String id(String x) { return x; } Can’t pass an Object to 2 or 4 3 isn’t type-safe (doesn’t pass type checking) Can pass a String to 1 but you get an Object back

CMSC Parametric Polymorphism, Again But id() doesn’t care about the type of x –It works for any type So parameterize the method: static T id(T x) { return x; } Integer i = id(new Integer(3)); –Notice no need to instantiate id; compiler figures out the correct type at usage –The formal parameter has type T, the actual parameter has type Integer

CMSC Standard Library, and Java 1.5 (and later) Part of Java 1.5 (called “generics”) –Comes with replacements for java.util.* class LinkedList {...} class HashMap {... } interface Collection {... } –Excellent tutorial listed on references page But they didn’t change the JVM to add generics – How did they do that?

CMSC Translation via Erasure Replace uses of type variables with Object –class A {...T x;... } becomes –class A {...Object x;... } Add downcasts wherever necessary –Integer x = A.get(); becomes –Integer x = (Integer) (A.get()); So why did we bother with generics if they’re just going to be removed? –Because the compiler still did type checking for us –We know that those casts will not fail at run time

CMSC Limitations of Translation Some type information not available at compile- time –Recall type variables T are rewritten to Object Disallowed, assuming T is type variable: –new T() would translate to new Object() (error) –new T[n] would translate to new Object[n] (warning) –Some casts/instanceofs that use T (Only ones the compiler can figure out are allowed)

CMSC Using with Legacy Code Translation via type erasure –class A becomes class A Thus class A is available as a “raw type” –class A {... } –class B { A x; } // use A as raw type Sometimes useful with legacy code, but... –Dangerous feature to use –Relies on implementation of generics, not semantics

CMSC Polymorphism Quiz #1 What kind of polymorphism? –Possible answers: subtype, parametric (classes or methods), or ad-hoc foo(x) takes floats and ints because the programmer provided two different versions of the function, one for each type int foo(int x) { return x+1; } float foo(float x) { return x+1.0; }

CMSC Polymorphism Quiz #2 What kind of polymorphism? –Possible answers: subtype, parametric (classes or methods), or ad-hoc foo(x) takes floats and ints because the function body does not perform any operation that constrains the type of x let foo x = x

CMSC Polymorphism Quiz #3 What kind of polymorphism? –Possible answers: subtype, parametric (classes or methods), or ad-hoc foo(x) takes Floats and Integers because both are subclasses of Numbers class Number { } class Float extends Number { } class Integer extends Number { } String foo(Number x) { return x.toString(); }

CMSC Polymorphism Quiz #4 What kind of polymorphism? –Possible answers: subtype, parametric (classes or methods), or ad-hoc foo(x) takes Floats and Integers because the programmer used generics T foo(T x) { return x; }

CMSC Polymorphism Quiz #5 What kind of polymorphism? –Possible answers: subtype, parametric (classes or methods), or ad-hoc the constructor for class Foo takes Floats and Integers because the programmer used generics class Foo { Foo(T x) { } }

CMSC Subtyping and Arrays Java has one interesting subtyping feature: –If S is a subtype of T, then –S[] is a subtype of T[]

CMSC Problem with Subtyping Arrays Program compiles without warning Java must generate run-time check at (1) to prevent (2) –Type written to array must be subtype of array contents 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 Subtyping for Generics Is Stack a subtype of Stack ? –We could have the same problem as with arrays –Thus Java forbids this subtyping Now consider the following method: –Not allowed to call count(x) where x has type Stack int count(Collection c) { int j = 0; for (Iterator i = c.iterator(); i.hasNext(); ) { Object e = i.next(); j++; } return j; }

CMSC int count(Collection c) { int j = 0; for (Iterator i = c.iterator(); i.hasNext(); ) { T e = i.next(); j++; } return j;} Solution I: Use Polymorphic Methods But requires a “dummy” type variable that isn’t really used for anything

CMSC Solution II: Wildcards Use ? as the type variable –Collection is “Collection of unknown” Why is this safe? –Using ? is a contract that you’ll never rely on having a particular parameter type –All objects subtype of Object, so assignment to e ok int count(Collection c) { int j = 0; for (Iterator i = c.iterator(); i.hasNext(); ) { Object e = i.next(); j++; } return j; }

CMSC Legal Wildcard Usage Reasonable question: –Stack is not a subtype of Stack –Why is Stack a subtype of Collection ? Answer: –Wildcards permit “reading” but not “writing”

CMSC Example: Can read but cannot write 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; }

Shapes Example Suppose we have classes Circle, Square, and Rectangle, all subtypes of Shape CMSC 330 Rectangle Square Circle Shape

CMSC More on Generic Classes Suppose we have the following method: –Can we pass this method a Collection ? No, not a subtype of Collection –How about the following? void drawAll(Collection c) { for (Shape s : c) s.draw(); } void drawAll(Collection c) { for (Shape s : c) s.draw(); } // not allowed, assumes ? is Shape

CMSC Bounded Wildcards We want drawAll to take a Collection of anything that is a subtype of shape –this includes Shape itself –This is a bounded wildcard –We can pass Collection –We can safely treat s as a Shape void drawAll(Collection c) { for (Shape s : c) s.draw(); }

CMSC Upper Bounded Wild Cards ? extends Shape actually gives an upper bound on the type accepted Shape is the upper bound of the wildcard Rectangle Square Circle Shape

CMSC Lower Bounded Wildcards Dual of the upper bounded wildcards ? super Rectangle denotes a type that is a supertype of Rectangle –Rectangle is included, and is a lower bound on the type accepted Rectangle Square Circle Shape

CMSC Lower Bounded Wildcards (cont’d) Example: –Because c is a Collection of something that is always compatible with Circle void foo(Collection c) { c.add(new Circle()); c.add(new Rectangle()); // fails }

CMSC Bounded Type Variables You can also add bounds to regular type vars –This method can take a List of any subclass of Shape This addresses some of the reason that we decided to introduce wild cards T getAndDrawShape(List c) { c.get(1).draw(); return c.get(2); }

Ruby “Generics” Does Ruby support parametric polymorphism? If so, how? CMSC 330

CMSC 330: Organization of Programming Languages Exceptions

CMSC Preconditions Functions often have requirements on their inputs // Return maximum element in A[i..j] int findMax(int[] A, int i, int j) {... } –A is nonempty –A isn't null –i and j must be nonnegative –i and j must be less than A.length –i < j (maybe) These are called preconditions

CMSC Dealing with Errors What do you do if a precondition isn’t met? What do you do if something unexpected happens? –Try to open a file that doesn’t exist –Try to write to a full disk

CMSC Signaling Errors Style 1: Return invalid value // Returns value key maps to, or null if no // such key in map Object get(Object key); –Disadvantages?

CMSC Signaling Errors (cont’d) Style 2: Return an invalid value and status static int lock_rdev(mdk_rdev_t *rdev) {... if (bdev == NULL) return -ENOMEM;... } // Returns NULL if error and sets global // variable errno FILE *fopen(const char *path, const char *mode);

CMSC Problems with These Approaches What if all possible return values are valid? –E.g., findMax from earlier slide What about errors in a constructor? What if client forgets to check for error? What if client can’t handle error? –Needs to be dealt with at a higher level Poor modularity- exception handling code becomes scattered throughout program 1996 Ariane 5 failure classic example of this …

CMSC Ariane 5 failure Design issues: In order to save funds and ensure reliability, and since the French Ariane 4 was a successful rocket, the Inertial Reference System (SRI) from Ariane 4 was reused for the Ariane 5. What happened?: On June 4, 1996 the Ariane 5 launch vehicle failed 39 seconds after liftoff causing the destruction of over $100 million in satellites. Cause of failure: The SRI, which controls the attitude (direction) of the vehicle by sending aiming commands to the rocket nozzle, sent a bad command to the rocket causing the nozzle to move the rocket toward the horizontal. The backup SRI had failed for the same reason 72 millisec earlier. The vehicle had to then be destroyed.

CMSC Why Ariane 5 failed SRI tried to convert a floating point number out of range to integer. Therefore it issued an error message (as a 16 bit number). This 16 bit number was interpreted as an integer by the guidance system and caused the nozzle to move accordingly. Ada range checking was disabled since the SRI was supposedly processing at 80% load and the extra time needed for range checking was deemed unnecessary since the Ariane 4 software worked well. The ultimate cause of the problem was that the Ariane 5 has a more pronounced angle of attack and can move horizontally sooner after launch. The “bad value” was actually the appropriate horizontal speed of the vehicle.

CMSC Better approaches: Exceptions in Java On an error condition, we throw an exception At some point up the call chain, the exception is caught and the error is handled Separates normal from error-handling code A form of non-local control-flow –Like goto, but structured

CMSC Throwing an Exception Create a new object of the class Exception, and throw it if (i >= 0 && i < a.length ) return a[i]; throw new ArrayIndexOutOfBounds(); Exceptions thrown are part of the return type in Java –When overriding method in superclass, cannot throw any more exceptions than parent’s version

CMSC Method throws declarations A method declares the exceptions it might throw public void openNext() throws UnknownHostException, EmptyStackException { … } Must declare any exception the method might throw –Unless it is caught in (masked by) the method –Includes exceptions thrown by called methods –Certain kinds of exceptions excluded

Java Exception Hierarchy CMSC 330 Throwable ExceptionError RuntimeException checkedunchecked

CMSC Checked Exceptions Represent invalid conditions in areas outside the immediate control of the program –Invalid user input –Database problems –Network outages –Absent files –etc. A method is obliged to establish a policy for all checked exceptions thrown by its implementation –Either pass the checked exception further up the stack, or handle it somehow

CMSC Unchecked Exceptions Represent defects in the program (bugs) Are subclasses of RuntimeException Common types: –IllegalArgumentException –NullPointerException –IllegalStateException A method is not obliged to establish a policy for the unchecked exceptions thrown by its implementation (and they almost always do not do so) These should not be encountered in production code if proper debugging was done

Errors Represent serious problems that a “reasonable” program shouldn’t attempt to handle –Assertions –Character set decoding issue –Class file linkage errors –JVM configuration errors –Out of virtual memory Are subclasses of Error A method is not obliged to establish a policy for errors CMSC 330

Java Exception Hierarchy CMSC 330 Throwable ExceptionError RuntimeException checkedunchecked

CMSC Implementing Exceptions in Java JVM knows about exceptions, and has built-in mechanism to handle them public class A { void foo() { try { Object f = null; f.hashCode(); } catch (NullPointerException e) { System.out.println("caught"); }

CMSC First catch with supertype of the exception catches it finally is always executed try { if (i == 0) return; myMethod(a[i]); } catch (ArrayIndexOutOfBounds e) { System.out.println(“a[] out of bounds”); } catch (MyOwnException e) { System.out.println(“Caught my error”); } catch (Exception e) { System.out.println(“Caught” + e.toString()); throw e; } finally { /* stuff to do regardless of whether an exception */ /* was thrown or a return taken */ } Exception Handling

CMSC Implementing Exceptions in Java Exception table tells JVM what handlers there are for which region of code void foo(); Code: 0: aconst_null 1: astore_1 2: aload_1 3: invokevirtual #2; //hashCode 6: pop 7: goto 19 10: astore_1 11: getstatic #4; //System.out 14: ldc #5; //String caught 16: invokevirtual #6; //println 19: return Exception table: from to target type NullPointerExn

CMSC Unhandled Exceptions Design battle: resumption vs. termination –Resumption: an exception handler can resume computation at the place where the exception was thrown –Termination: throwing an exception terminates execution at the point of the exception Resumption is risky, but so is termination –What do you think?

Issues with Exceptions Exceptions are essentially a return to GOTO statements –Very hard to analyze statically –See Djikstra’s famous 1968 letter “Go To Statement Considered Harmful” for other reasons why GOTO statements are a bad idea We can try to more formally and completely describe our preconditions, but sometimes this is too difficult In practice, exceptions are usually the best solution CMSC 330