DOC PREVIEW
Berkeley COMPSCI 61B - Lecture Notes

This preview shows page 1 out of 2 pages.

Save
View full document
View full document
Premium Document
Do you want full access? Go Premium and unlock all 2 pages.
Access to all documents
Download any document
Ad free experience
Premium Document
Do you want full access? Go Premium and unlock all 2 pages.
Access to all documents
Download any document
Ad free experience

Unformatted text preview:

02/26/1417:33:29 116 CS 61B: Lecture 16 Wednesday, February 26, 2014Today’s reading: Sierra & Bates, pp. 189, 283.EXCEPTIONS (continued)==========The "finally" keyword---------------------A finally clause can also be added to a "try." FileInputStream f = new FileInputStream("filename"); try { statementX; return 1; } catch (IOException e) { e.printStackTrace(); return 2; } finally { f.close(); }If the "try" statement begins to execute, the "finally" clause will be executedat the end, no matter what happens. "finally" clauses are used to do thingsthat need to be done in both normal and exceptional circumstances.In this example, it is used to close a file.If statementX causes no exception, then the "finally" clause is executed, and1 is returned.If statementX causes a IOException, the exception is caught, the "catch"clause is executed, and then the "finally" clause is executed. After the"finally" clause is done, 2 is returned.If statementX causes some other class of exception, the "finally" clause isexecuted immediately, then the exception continues to propagate down the stack.In the example above, we’ve invoked the method "printStackTrace" on theexception we caught. When an exception is constructed, it takes a snapshot ofthe stack, which can be printed later.It is possible for an exception to occur in a "catch" or "finally" clause. Anexception thrown in a "catch" clause will terminate the "catch" clause, but the"finally" clause will still get executed before the exception goes on. Anexception thrown in a "finally" clause replaces the old exception, andterminates the "finally" clause and the method immediately.However...you can nest a "try" clause inside a "catch" or "finally" clause,thereby catching those exceptions as well.Exception constructors----------------------By convention, most Throwables (including Exceptions) have two constructors.One takes no parameters, and one takes an error message in the form of aString. class MyException extends Exception { public MyException() { super(); } public MyException(String s) { super(s); } }The error message will be printed if it propagates out of main(), and it can beread by the Throwable.getMessage() method. The constructors usually call thesuperclass constructors, which are defined in Throwable.GENERICS========Suppose you’re using a list of Objects to store Strings. When you fetch aString from the list, you have to cast it back to type "String" before you cancall the methods exclusive to Strings. If somehow an object that’s not aString got into your list, the cast will throw an exception. It would be niceto have the compiler enforce the restriction that nothing but Strings can everget into your list in the first place, so you can sleep at night knowing thatyour family is safe from a ClassCastException.So Java offers _generics_, which allow you to declare general classes thatproduce specialized objects. For example, you can create an SList for Stringsonly, and another SList for Integers only, even though you only wrote oneSList class. To specify the class, SList takes a _type_parameter_.class SListNode<T> { // T is the formal parameter. T item; SListNode<T> next; SListNode(T i, SListNode<T> n) { item = i; next = n; }}public class SList<T> { SListNode<T> head; public void insertFront(T item) { head = new SListNode<T>(item, head); }}You can now create and use an SList of Strings as follows. SList<String> l = new SList<String>(); // String is the actual parameter. l.insertFront("Hello");Likewise, you can create an SList of Integers by using "SList<Integer>" in thedeclaration and constructor.What are the advantages of generics? First, the compiler will ensure atcompile-time that nothing but Strings can ever enter your SList<String>.Second, you don’t have to cast the Objects coming out of your SList back toStrings, so there is no chance of an unexpected ClassCastException at run time.If some bug in your program is trying to put Integer objects into your SList,it’s much easier to diagnose the compiler refusing to put an Integer into anSList<String> than it is to diagnose a ClassCastException occurring when youremove an Integer from a regular SList and try to cast it to String.Generics are a complicated subject. Consider this to be a taste of them;hardly a thorough treatment. A good tutorial is available athttps://www.seas.upenn.edu/˜cis1xx/resources/generics-tutorial.pdf .Although Java generics are superficially similar to C++ templates, there’s acrucial difference between them. In the example above, Java compiles bytecodefor only a single SList class. This SList bytecode can be used by alldifferent object types. It is the compiler, not the bytecode itself, thatenforces the fact that a particular SList object can only store objects of aparticular class. Conversely, C++ recompiles the SList methods for every typethat you instantiate SLists on. The C++ disadvantage is that one class mightturn into a lot of machine code. The C++ advantages are that you can useprimitive types, and you get code optimized for each type. Java generics don’twork with primitive types.02/26/1417:33:29 216FIELD SHADOWING===============Just as methods can be overridden in subclasses, fields can be "shadowed" insubclasses. However, shadowing works quite differently from overriding.Whereas the choice of methods is dictated by the _dyanamic_type_ of an object,the choice of fields is dictated by the _static_type_ of a variable or object. class Super { int x = 2; int f() { return 2; } } class Sub extends Super { int x = 4; // shadows Super.x int f() { // overrides Super.f() return 4; } }Any object of class Sub now has _two_ fields called x, each of which store adifferent integer. How do we know which field is accessed when we refer to x?It depends on the static type of the expression whose x field is accessed. Sub sub = new Sub(); Super supe = sub; // supe and sub reference the same object. int i; ---------------- --- | --- --- | --- |.+--->| |4| |2| |<---+.| --- | --- --- | --- sub |Sub.x Super.x | supe ---------------- i = supe.x; // 2 i =


View Full Document

Berkeley COMPSCI 61B - Lecture Notes

Documents in this Course
Lab

Lab

4 pages

Matrix

Matrix

3 pages

Numbers

Numbers

14 pages

Lectures

Lectures

12 pages

Project 1

Project 1

24 pages

Exam

Exam

8 pages

Load more
Download Lecture Notes
Our administrator received your request to download this document. We will send you the file to your email shortly.
Loading Unlocking...
Login

Join to view Lecture Notes and access 3M+ class-specific study document.

or
We will never post anything without your permission.
Don't have an account?
Sign Up

Join to view Lecture Notes 2 2 and access 3M+ class-specific study document.

or

By creating an account you agree to our Privacy Policy and Terms Of Use

Already a member?