Download presentation
Presentation is loading. Please wait.
Published byStephany Harrison Modified over 8 years ago
1
CS 152: Programming Language Paradigms April 23 Class Meeting Department of Computer Science San Jose State University Spring 2014 Instructor: Ron Mak www.cs.sjsu.edu/~mak
2
SJSU Dept. of Computer Science Spring 2014: April 23 CS 152: Programming Language Paradigms © R. Mak 2 Comparing Objects of the Same Type If a reference class implements the Comparable interface, then you can compare instances (objects) of that class to each other. You have to implement the interface’s compareTo() method. For example, we can define shape objects such as squares, rectangles, and circles and compare their areas. _
3
SJSU Dept. of Computer Science Spring 2014: April 23 CS 152: Programming Language Paradigms © R. Mak 3 Abstract Class SimpleShape Abstract base class SimpleShape implements the Comparable interface. It implements the interface’s compareTo() method. It returns a negative, zero, or positive int value if the comparison is less than, equal to, or greater than, respectively. Subclasses will implement method area(). public abstract class SimpleShape implements Comparable { public abstract float area(); public int compareTo(Object other) { return (int) (this.area() - ((SimpleShape) other).area()); } } Comparable is a raw interface. Type casting needed.
4
SJSU Dept. of Computer Science Spring 2014: April 23 CS 152: Programming Language Paradigms © R. Mak 4 Subclass Square Subclass Square implements method area(). public class Square extends SimpleShape { private float width; public Square(float width) { this.width = width; } public float area() { return width*width; } }
5
SJSU Dept. of Computer Science Spring 2014: April 23 CS 152: Programming Language Paradigms © R. Mak 5 Subclass Rectangle Subclass Rectangle has its implementation of method area(). public class Rectangle extends SimpleShape { private float width, height; public Rectangle(int width, int height) { this.width = width; this.height = height; } public float area() { return width*height; } }
6
SJSU Dept. of Computer Science Spring 2014: April 23 CS 152: Programming Language Paradigms © R. Mak 6 Subclass Circle Finally, subclass Circle has its implementation of method area(). public class Circle extends SimpleShape { private static final float PI = 3.1415926f; private float radius; public Circle(float radius) { this.radius = radius; } public float area() { return PI*radius*radius; } }
7
SJSU Dept. of Computer Science Spring 2014: April 23 CS 152: Programming Language Paradigms © R. Mak 7 Array5: SimpleShape Objects public static void main(String[] args) { ArrayList shapes = new ArrayList<>(); shapes.add(new Square(5)); shapes.add(new Rectangle(3, 4)); shapes.add(new Circle(2)); System.out.print("Before sorting:"); print(shapes); sort(shapes); System.out.print(" After sorting:"); print(shapes); }
8
SJSU Dept. of Computer Science Spring 2014: April 23 CS 152: Programming Language Paradigms © R. Mak 8 Array5: SimpleShape Objects, cont’d private static void print(ArrayList elements) { for (SimpleShape elmt : elements) { System.out.print(" " + elmt); } System.out.println(); } private static void sort(ArrayList elements) { for (int i = 0; i < elements.size()-1; i++) { for (int j = i+1; j < elements.size(); j++) { if (elements.get(j).compareTo(elements.get(i)) < 0) { SimpleShape temp = elements.get(i); elements.set(i, elements.get(j)); elements.set(j, temp); } } } }
9
SJSU Dept. of Computer Science Spring 2014: April 23 CS 152: Programming Language Paradigms © R. Mak 9 Array6: Comparable Type coercion is no longer needed! public abstract class SimpleShape implements Comparable { public abstract float area(); public int compareTo(SimpleShape other) { return (int) (this.area() - other.area()); } }
10
SJSU Dept. of Computer Science Spring 2014: April 23 CS 152: Programming Language Paradigms © R. Mak 10 Java Arrays are Covariant Square is a subclass of class SimpleShape. Therefore, Square objects are assignment compatible with SimpleShape objects. Java arrays are covariant. In this example, a Square[] array is assignment compatible with a SimpleShape[] array. _
11
SJSU Dept. of Computer Science Spring 2014: April 23 CS 152: Programming Language Paradigms © R. Mak 11 Java Arrays are Covariant, cont’d private static float totalArea(SimpleShape elements[]) { float total = 0; for (Shape elmt : elements) { total += elmt.area(); } return total; } The parameter type is SimpleShape[].
12
SJSU Dept. of Computer Science Spring 2014: April 23 CS 152: Programming Language Paradigms © R. Mak 12 Java Arrays are Covariant, cont’d public static void main(String[] args) { SimpleShape shapes[] = new Shape[] { new Square(5), new Rectangle(3, 4), new Circle(2) }; System.out.println("Total area: " + totalArea(shapes)); Square squares[] = new Square[] { new Square(5), new Square(3), new Square(2) }; System.out.println("Total area: " + totalArea(squares)); } Because Square is assignment compatible with SimpleShape, we can pass an actual Square[] value for a SimpleShape[] parameter. Demo
13
SJSU Dept. of Computer Science Spring 2014: April 23 CS 152: Programming Language Paradigms © R. Mak 13 When Bad Things Happen at Run Time Synchronous errors Errors caused by program actions, such as Null pointer exception. Array index out of bounds. Division by zero. File not found. Out of memory. Your program can catch and handle these errors.
14
SJSU Dept. of Computer Science Spring 2014: April 23 CS 152: Programming Language Paradigms © R. Mak 14 When Bad Things Happen at Run Time, cont’d Asynchronous errors Errors caused by events external to your program, such as Forced process termination Hardware failures Not much your program can do about these errors. _
15
SJSU Dept. of Computer Science Spring 2014: April 23 CS 152: Programming Language Paradigms © R. Mak 15 Traditional Runtime Error Handling Detect that if your program performs an operation, it will cause a runtime error. Therefore, don’t perform the operation. Issue an error message and/or return an error code. But what if an error has already occurred? if (divisor == 0) { System.err.println("*** Error: Division by zero."); return ERROR_CODE_DIVISION_BY_ZERO; } else { ratio = dividend/divisor;... }
16
SJSU Dept. of Computer Science Spring 2014: April 23 CS 152: Programming Language Paradigms © R. Mak 16 Runtime Exception Handling Virtually all major current languages have built-in exception-handling mechanisms. Yes: Java, C++, Python, Common Lisp, Scheme No: C, Smalltalk Pioneered by the language PL/I in the 1960s. _
17
SJSU Dept. of Computer Science Spring 2014: April 23 CS 152: Programming Language Paradigms © R. Mak 17 Runtime Exception Handling, cont’d Exception handling attempts to imitate the features of a hardware interrupt or error trap. If the underlying machine or operating system is left to handle the runtime error, the program will usually abort or crash. Programs that crash are not robust. Robust programs can withstand runtime errors, recover, and continue to run. _
18
SJSU Dept. of Computer Science Spring 2014: April 23 CS 152: Programming Language Paradigms © R. Mak 18 Exception Objects An exception (runtime error) is represented in most modern languages by an object. This object is instantiated as needed from an exception class. Exception classes can be part of a hierarchy. Example (Java): Object-Oriented Design & Patterns by Cay Horstmann John Wiley & Sons, 2006.
19
SJSU Dept. of Computer Science Spring 2014: April 23 CS 152: Programming Language Paradigms © R. Mak 19 Exception Objects, cont’d The exception object can contain useful information about an exception. Where it occurred Error message Erroneous value _
20
SJSU Dept. of Computer Science Spring 2014: April 23 CS 152: Programming Language Paradigms © R. Mak 20 Runtime Exception Handling Both Java and C++ have try-catch constructs. Example (Java): Execute code that can throw (cause) an exception inside the try block. The exception can occur directly in the block or in a method called from the block. try { code that may throw exceptions } catch (ExceptionType1 ex1) { handler for ExceptionType1 } catch (ExceptionType2 ex2){ handler for ExceptionType2 }
21
SJSU Dept. of Computer Science Spring 2014: April 23 CS 152: Programming Language Paradigms © R. Mak 21 Runtime Exception Handling, cont’d A catch clause gains control after the try block throws an exception object that belongs to the class of the catch clause or to one of its subclasses. Example: catch (IOException ex) will also catch FileNotFoundException objects. try { code that may throw exceptions } catch (ExceptionType1 ex1) { handler for ExceptionType1 } catch (ExceptionType2 ex2){ handler for ExceptionType2 }
22
SJSU Dept. of Computer Science Spring 2014: April 23 CS 152: Programming Language Paradigms © R. Mak 22 The Exception Object The exception object can contain useful information. Example: Use the object to print a stack trace. try {... } catch (Exception ex) { // catch any exception ex.printStackTrace(); }
23
SJSU Dept. of Computer Science Spring 2014: April 23 CS 152: Programming Language Paradigms © R. Mak 23 Resumption vs. Termination Models Suppose we catch an exception. After the catch clause has executed, where does control go next? _
24
SJSU Dept. of Computer Science Spring 2014: April 23 CS 152: Programming Language Paradigms © R. Mak 24 Resumption vs. Termination Models, cont’d Resumption model Control returns to where the exception was thrown. Not found in most modern languages.
25
SJSU Dept. of Computer Science Spring 2014: April 23 CS 152: Programming Language Paradigms © R. Mak 25 Resumption vs. Termination Models, cont’d Termination model Control continues with the code following the try-catch block. Example: while (true) { // loop forever try { // keep trying to allocate memory X x = new X; break; // succeeded, so exit loop } catch (OutOfMemoryException ex) { garbageCollection(); if ( /* still insufficient memory */ ) { // rethrow exception to exit loop throw new OutOfMemoryException(); } // else loop to try again to allocate } }
26
SJSU Dept. of Computer Science Spring 2014: April 23 CS 152: Programming Language Paradigms © R. Mak 26 Exception Propagation Suppose an exception can occur in a method, but the method does not have a catch clause to catch it. The method must declare that it can throw the exception (or a superclass of the exception). The method propagates the exception to its caller. The exception must be caught by the caller of the method, or the caller must declare that it can throw the exception, etc. _
27
SJSU Dept. of Computer Science Spring 2014: April 23 CS 152: Programming Language Paradigms © R. Mak 27 Exception Propagation, cont’d If an exception thrown by a method is caught several callers back in the call chain, call unwinding occurs. _
28
SJSU Dept. of Computer Science Spring 2014: April 23 CS 152: Programming Language Paradigms © R. Mak 28 Programmer-Defined Exceptions You can define application-specific exception classes by subclassing from java.lang.Throwable or from any of the predefined exception classes. Example: class MyException extends Throwable {... } try {... if ( /* error occurred */ { throw new MyException(...); }... } catch (MyException ex) {... }
29
SJSU Dept. of Computer Science Spring 2014: April 23 CS 152: Programming Language Paradigms © R. Mak 29 Runtime Procedure Activation Recall how the runtime stack and the runtime display manage activation records as procedures (methods) are called and returned from. RUNTIME STACK (define proc (lambda (a b) (let ((sum (+ a (func b)))) sum) )) (define func (lambda (a) (let* ((b 2) (prod (* a b))) prod) )) (define x 2) (define y 3) (proc x y) RUNTIME DISPLAY 1 2 3 AR: main xy 1 AR: lambda ab 2 AR: let sum 3 AR: lambda a 2 AR: let* bprod 3
30
SJSU Dept. of Computer Science Spring 2014: April 23 CS 152: Programming Language Paradigms © R. Mak 30 Parameter-Passing Mechanisms How are parameters passed from one method to another during a call? In other words, how are values transferred from one activation record to the next? Two definitions Actual parameter: An argument in a call. Formal parameter: An argument in a method declaration. _
31
SJSU Dept. of Computer Science Spring 2014: April 23 CS 152: Programming Language Paradigms © R. Mak 31 Parameter-Passing Mechanisms, cont’d Four primary parameter passing mechanisms: Pass by value (AKA call by value) Pass by reference (AKA call by reference) Pass by value-result (AKA call by value-result) Pass by name (AKA call by name) _
32
SJSU Dept. of Computer Science Spring 2014: April 23 CS 152: Programming Language Paradigms © R. Mak 32 Pass by Value Pass by value is most common. Pass a copy of the value of the actual parameter to the corresponding formal parameter. The called method can make changes to its copy of the parameter value. Changes made to a formal parameter by the called method do not affect the value of the actual parameter in the caller. _
33
SJSU Dept. of Computer Science Spring 2014: April 23 CS 152: Programming Language Paradigms © R. Mak 33 Pass by Value, cont’d Pass by value is the default with C++. Pass by value can be expensive if the actual parameter is a large structure. The entire struct is copied. Note that C++ passes by value a reference to an array. _ Demo
34
SJSU Dept. of Computer Science Spring 2014: April 23 CS 152: Programming Language Paradigms © R. Mak 34 Java Pass by Value Pass by value is the only parameter passing mechanism supported by Java. Subtle distinction: When Java passes an object, it passes by value a reference to the object. The called method can change field values of the passed object using its copy of the reference. But it cannot change what object the actual parameter refers to. _ Demo
35
SJSU Dept. of Computer Science Spring 2014: April 23 CS 152: Programming Language Paradigms © R. Mak 35 Pass by Reference An option in C++. Specify that a parameter is to be passed by reference by prefixing the formal parameter name with &. It’s possible to create multiple aliases. _
36
SJSU Dept. of Computer Science Spring 2014: April 23 CS 152: Programming Language Paradigms © R. Mak 36 Pass by Reference, cont’d void proc(int &x, int &y, int &z) { x = 1; y = 2; z = x + y; } int main() { int i = 12; proc(i, i, i); } What is the value of i after the call to proc ? Demo 4
37
SJSU Dept. of Computer Science Spring 2014: April 23 CS 152: Programming Language Paradigms © R. Mak 37 Pass by Value-Result A copy of the actual parameter value is passed to the formal parameter. Just like pass by value. Upon return from the procedure, the current value of the formal parameter is copied back into the actual parameter. Therefore, during the execution of the procedure, the value of the actual parameter (if it is accessible) is unchanged.
38
SJSU Dept. of Computer Science Spring 2014: April 23 CS 152: Programming Language Paradigms © R. Mak 38 Pass by Value-Result, cont’d Implemented by in-out parameters in the Ada language. _
39
SJSU Dept. of Computer Science Spring 2014: April 23 CS 152: Programming Language Paradigms © R. Mak 39 Pass by Name Originally implemented by Algol 60 as a way to do inline procedures. Replace the name of a formal parameter used within a procedure by the text of the actual parameter. A lazy evaluation mechanism. The actual parameter is not evaluated until the name of the corresponding formal parameter is encountered at run time. _
40
SJSU Dept. of Computer Science Spring 2014: April 23 CS 152: Programming Language Paradigms © R. Mak 40 Pass by Name, cont’d Suppose C used pass by name. What happens to array a ? int i; int a[2]; void inc(int x) { i++; x++; } int main() { i = 0; a[0] = 0; a[1] = 1; inc(a[i]); return 0; } int i; int a[2]; void inc(int x) { i++; a[i]++; } int main() { i = 0; a[0] = 0; a[1] = 1; inc(a[i]); return 0; } a[0] = 0 a[1] = 2 Pass-by-name parameters are evaluated as small functions called “thunks”. A thunk executes in the context of the caller.
41
SJSU Dept. of Computer Science Spring 2014: April 23 CS 152: Programming Language Paradigms © R. Mak 41 Pass by Name, cont’d Pass by name: What value will be printed? int i; int p(int y) { int j = y; i++; return j + y; } void q() { int j = 2; i = 0; printf("%d\n", p(i + j)); } main() { q(); } int i; int p(int y) { int j = i + j; i++; return j + i + j; } void q() { int j = 2; i = 0; printf("%d\n", p(i + j)); } main() { q(); } 022 1 2 2 5
42
SJSU Dept. of Computer Science Spring 2014: April 23 CS 152: Programming Language Paradigms © R. Mak 42 Pass by Name, cont’d Pass by name: Does this swap procedure work? void swap(int x, int y) { int temp = x; x = y; y = temp; } int i; int j; swap(i, j); int i; int a[10]; swap(i, a[i]); int temp = i; i = j; j = temp; int temp = i; i = a[i]; a[i] = temp; Yes! Oops!
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.