CS61B Lecture #12: Delegation, Exceptions, Assorted Features
Delegation Exceptions Importing Nested classes. Type testing.
Last modified: Wed Feb 16 15:16:53 2022
CS61B: Lecture #12 1
Copyright By PowCoder代写 加微信 powcoder
Trick: Delegation and Wrappers
Not always appropriate to use inheritance to extend something.
Homework gives example of a TrReader, which contains another Reader, to which it delegates the task of actually going out and reading characters.
Another example: a class that instruments objects:
interface Storage { void put(Object x); Object get();
class Monitor implements Storage {
int gets, puts;
private Storage store;
Monitor(Storage x) { store = x; gets = puts = 0; } public void put(Object x) { puts += 1; store.put(x); } public Object get() { gets += 1; return store.get(); }
// ORIGINAL
Storage S = something; f(S);
Monitor is called a wrapper class. Last modified: Wed Feb 16 15:16:53 2022
// INSTRUMENTED
Monitor S = new Monitor(something); f(S);
System.out.println(S.gets + ” gets”);
CS61B: Lecture #12 2
What to do About Errors?
Large amount of any production program devoted to detecting and responding to errors.
Some errors are external (bad input, network failures); others are internal errors in programs.
When method has stated precondition, it’s the client’s job to comply. Still, it’s nice to detect and report client’s errors.
In Java, we throw exception objects, typically:
throw new SomeException(optional description);
Exceptions are objects. By convention, they are given two constructors: one with no arguments, and one with a descriptive string argument (which the exception stores).
Java system throws some exceptions implicitly, as when you dereference a null pointer, or exceed an array bound.
Last modified: Wed Feb 16 15:16:53 2022 CS61B: Lecture #12 3
Catching Exceptions
A throw causes each active method call to terminate abruptly, until
(and unless) we come to a try block.
Catch exceptions and do something corrective with try:
Stuff that might throw exception;
} catch (SomeException e) { Do something reasonable;
} catch (SomeOtherException e) { Do something else reasonable;
Go on with life;
When SomeException exception occurs during “Stuff. . . ” and is not handled there, we immediately “do something reasonable” and then “go on with life.”
Descriptive string (if any) available as e.getMessage() for error messages and the like.
Last modified: Wed Feb 16 15:16:53 2022 CS61B: Lecture #12 4
Catching Exceptions, II
Using a supertype as the parameter type in a catch clause will catch
any subtype of that exception as well:
Code that might throw a FileNotFoundException or a
MalformedURLException ; } catch (IOException ex) {
Handle any kind of IOException; }
Since FileNotFoundException and MalformedURLException both inherit from IOException, the catch handles both cases.
Subtyping means that multiple catch clauses can apply; Java takes the first.
Stylistically, it’s nice to be more specific (concrete) about exception types where possible.
In particular, our style checker will therefore balk at the use of Exception, RuntimeException, Error, and Throwable as exception supertypes.
Last modified: Wed Feb 16 15:16:53 2022 CS61B: Lecture #12 5
Catching Exceptions, III
There’s a relatively new shorthand for handling multiple exceptions the same way:
Code that might throw IllegalArgumentException
or IllegalStateException;
} catch (IllegalArgumentException|IllegalStateException ex) {
Handle exception; }
Last modified: Wed Feb 16 15:16:53 2022 CS61B: Lecture #12 6
Exceptions: Checked vs. Unchecked
The object thrown by throw command must be a subtype of Throwable
(in java.lang).
Java pre-declares several such subtypes, among them
– Error, used for serious, unrecoverable errors;
– Exception, intended for all other exceptions;
– RuntimeException, a subtype of Exception intended mostly for programming errors too common to be worth declaring.
Pre-declared exceptions are all subtypes of one of these.
Any subtype of Error or RuntimeException is said to be unchecked. All other exception types are checked.
Last modified: Wed Feb 16 15:16:53 2022 CS61B: Lecture #12 7
Unchecked Exceptions
– Programmer errors: many library functions throw
IllegalArgumentException when one fails to meet a precondition. – Errors detected by the basic Java system: e.g.,
Executing x.y when x is null,
Executing A[i] when i is out of bounds,
Executing(String) xwhenxturnsoutnottopointtoaString.
– Certain catastrophic failures, such as running out of memory. May be thrown anywhere at any time with no special preparation.
Intended for
Last modified: Wed Feb 16 15:16:53 2022 CS61B: Lecture #12 8
Checked Exceptions
Intended to indicate exceptional circumstances that are expected to happen from time to time. Examples:
– Attempting to open a file that does not exist. – Input or output errors on a file.
– Receiving an interrupt.
Every checked exception that can occur inside a method must either be handled by a try statement, or reported in the method’s declaration.
For example,
void myRead() throws IOException, InterruptedException { … } means that myRead (or something it calls) might throw IOException
or InterruptedException.
Last modified: Wed Feb 16 15:16:53 2022 CS61B: Lecture #12 9
A Language Design Issue
Java makes the following illegal for checked exceptions like IOException. Why?
class Parent { class Child extends Parent {
void f() { … } void f() throws IOException { … }
Last modified: Wed Feb 16 15:16:53 2022 CS61B: Lecture #12 10
void f() { … } }}
Consider, for example,
void f() throws IOException { … }
A Language Design Issue
Java makes the following illegal for checked exceptions like IOException. Why?
class Parent { class Child extends Parent {
static void process(Parent p) { p.f();
According to the specification for class Parent, this is supposed to be OK, but the call p.f() actually calls Child.f, which might throw IOException. So contrary to the intent of checked exceptions, the process method might throw a checked exception that it does not list.
Last modified: Wed Feb 16 15:16:53 2022 CS61B: Lecture #12 11
Good Practice
Throw exceptions rather than using print statements and System.exit everywhere,
. . . because response to a problem may depend on the caller, not just method where problem arises.
Nice to throw an exception when programmer violates preconditions.
Particularly good idea to throw an exception rather than let bad input corrupt a data structure.
Good idea to document when methods throw exceptions.
To convey information about the cause of exceptional condition, put it into the exception rather than into some global variable:
class MyBad extends Exception { public IntList errs;
MyBad(IntList nums) { errs=nums; }
} catch (MyBad e) {
… e.errs …
Last modified: Wed Feb 16 15:16:53 2022 CS61B: Lecture #12 12
Terminology
Many students speak of “throwing” an error when they mean “throwing an exception in order to report an error.”
This is a confusion of implementation (the code a program uses to internally signal an exceptional condition) with visible behavior (printing an error message).
Users are not supposed to see them, but rather the messages that interpret these exceptions and report the exceptional conditions:
Good: Program prints
File myData.txt not found.
Bad: Program prints
Exception in thread “main” java.io.IOException: File not found
at foo.main(foo.java:4)
Last modified: Wed Feb 16 15:16:53 2022 CS61B: Lecture #12 13
Writing java.util.List every time you mean List or java.lang.regex.Pattern every time you mean Pattern is annoying.
The purpose of the import clause at the beginning of a source file is to define abbreviations:
–import java.util.List;means“withinthisfile,youcanuseList as an abbreviation for java.util.List.
– import java.util.*; means “within this file, you can use any class name in the package java.util without mentioning the package.”
Importing does not grant any special access; it only allows abbreviation. In effect, your program always contains import java.lang.*;
Last modified: Wed Feb 16 15:16:53 2022 CS61B: Lecture #12 14
Static importing
One can easily get tired of writing System.out and Math.sqrt. Do you really need to be reminded with each use that out is in the java.lang.System package and that sqrt is in the Math package (duh)?
Both examples are of static members. A feature of Java allows you to abbreviate such references:
– import static java.lang.System.out; means “within this file, you can use out as an abbreviation for System.out.
–import static java.lang.System.*;means“withinthisfile,you can use any static member name in System without mentioning the package.
Again, this is only an abbreviation. No special access.
Alas, you can’t do this for classes in the anonymous package.
Last modified: Wed Feb 16 15:16:53 2022 CS61B: Lecture #12 15
Nesting Classes
Sometimes, it makes sense to nest one class in another. The nested class might
– be used only in the implementation of the other, or – be conceptually “subservient” to the other
Nesting such classes can help avoid name clashes or “pollution of the name space” with names that will never be used anywhere else.
Example: Polynomials can be thought of as sequences of terms. Assuming that terms aren’t used outside of Polynomials, you might define a class to represent a term inside the Polynomial class:
class Polynomial { methods on polynomials
private Term[] terms; private static class Term {
Last modified: Wed Feb 16 15:16:53 2022
CS61B: Lecture #12 16
Inner Classes
Last slide showed a static nested class. Static nested classes are just like any other, except that they can be private or protected, and they can see private variables of the enclosing class.
Non-static nested classes are called inner classes.
Used when each instance of the nested class is created by and naturally associated with an instance of the containing class, like Banks and Accounts:
Last modified: Wed Feb 16 15:16:53 2022
CS61B: Lecture #12 17
Example: Banks and Accounts
class Bank {
private void addFunds(int amount) { totalFunds += amount; }
public class Account { int balance;
public void deposit(int amount) { balance += amount;
Bank.this.addFunds( balance);
} // Bank.this means “the bank that created me”
—————————————————
Bank bank = new Bank(…);
Bank.Account a0 = bank.new Account(…);
Bank.Account a1 = bank.new Account(…);
Last modified: Wed Feb 16 15:16:53 2022
CS61B: Lecture #12 18
Example: Iterators
public class ArrayList
public T get(int k) { … } public int size() { … }
public Iterator
return new ArrayIterator
// or return this.new ArrayIterator
private class ArrayIterator implements Iterator
ArrayIterator() { k = 0; }
public boolean hasNext() { return k < size(); } publicTnext(){ k+=1;returnget(k-1);}
Last modified: Wed Feb 16 15:16:53 2022 CS61B: Lecture #12 19
Type testing: instanceof
It is possible to ask about the dynamic type of something:
void typeChecker(Reader r) { if (r instanceof TrReader)
System.out.print("Translated characters: ");
System.out.print("Characters: ");
However, this is seldom what you want to do. Why do this:
if (x instanceof StringReader) read from (StringReader) x;
else if (x instanceof FileReader) read from (FileReader) x;
when you can just call x.read()?!
In general, use instance methods rather than instanceof.
Last modified: Wed Feb 16 15:16:53 2022 CS61B: Lecture #12 20
CS61B Lecture #14: Packages, Access
Last modified: Tue Feb 15 15:15:08 2022 CS61B: Lecture #14 1
Package Mechanics
Classes correspond to things being modeled (represented) in one’s program.
Packages are collections of “related” classes and other packages. Java puts standard libraries and packages in package java and javax. By default, a class resides in the anonymous package.
To put it elsewhere, use a package declaration at start of file, as in
package database; or package ucb.util;
Oracle’s javac uses convention that class C in package P1.P2 goes in
subdirectory P1/P2 of any other directory in the class path . Unix example:
export CLASSPATH=.: HOME/java-utils: MASTERDIR/lib/classes/junit.jar java junit.textui.TestRunner MyTests
Searches for TestRunner.class in ./junit/textui, ~/java-utils/junit/textui and finally looks for junit/textui/TestRunner.class in the junit.jar
file (which is a single file that is a special compressed archive of an entire directory of files).
Last modified: Tue Feb 15 15:15:08 2022 CS61B: Lecture #14 2
Access Modifiers
Access modifiers (private, public, protected) do not add anything
to the power of Java.
Basically allow a programmer to declare which classes are supposed to need to access (“know about”) what declarations.
In Java, are also part of security—prevent programmers from accessing things that would “break” the runtime system.
Accessibility always determined by static types.
– To determine correctness of writing x.f(), look at the definition
of f in the static type of x.
– Why the static type? Because the rules are supposed to be enforced by the compiler, which only knows static types of things (static types don’t depend on what happens at execution time).
Last modified: Tue Feb 15 15:15:08 2022 CS61B: Lecture #14 3
The Access Rules: Public
Accessibility of a member depends on (1) how the member’s declaration is qualified and (2) where it is being accessed.
C1, C2, C3, and C4 are distinct classes.
Class C2a is either class C2 itself or a subtype of C2.
package P1;
public class C1 ... {
// M is a method, field,...
public int M ...
void h(C1 x)
{ ... x.M ... } // OK. }
------------------------------ package P1;
public class C4 ... {
void p(C1 x)
{ ... x.M ... } // OK.
package P2;
class C2 extends C3 {
void f(P1.C1 x) {... x.M ...} // OK
void g(C2a y) {... y.M ... } // OK }
Last modified: Tue Feb 15 15:15:08 2022
CS61B: Lecture #14 4
Public members are available everywhere.
------------------------------
package P1;
The Access Rules: Private
C1, C2, and C4 are distinct classes.
Class C2a is either class C2 itself or a subtype of C2.
package P1;
public class C1 ...
package P2;
class C2 extends C1 {
void f(P1.C1 x) {... x.M ...} // ERROR
void g(C2a y) {... y.M ... } // ERROR }
// M is a method,
private int M ...
void h(C1 x)
{ ... x.M ... }
Private members are available only within the text of the same class, even for subtypes.
public class C4 ...
void p(C1 x)
{ ... x.M ... }
Last modified: Tue Feb 15 15:15:08 2022
CS61B: Lecture #14 5
Private to a Class, Not an Object
Consider a simple list implementation using linking:
public class LinkedList { private Node head;
private static class Node { Object head;
Node tail; }
/** Swap the contents of this LinkedList and OTHER. */
public void swap(LinkedList other) {
LinkedList tmp = other. head; other. head = head; head = tmp;
This is an obvious and correct implementation of swap, even though it fetches a private member of a LinkedList object other than this.
It is perfectly OK to do so by the rules, because swap is in the text of LinkedList and therefore has access to all private fields.
That is, “privacy” does not apply to individual objects, only to classes. Last modified: Tue Feb 15 15:15:08 2022 CS61B: Lecture #14 6
The Access Rules: Package Private
C1, C2, and C4 are distinct classes.
Class C2a is either class C2 itself or a subtype of C2.
package P1;
public class C1 ... {
// M is a method, field,...
void h(C1 x)
{ ... x.M ... } // OK. }
------------------------------
package P1;
package P2;
class C2 extends C1 {
void f(P1.C1 x) {... x.M ...} // ERROR
void g(C2a y) {... y.M ... } // ERROR }
Package Private members are available only within the same package (even for subtypes).
public class C4 ...
void p(C1 x)
{ ... x.M ... }
Last modified: Tue Feb 15 15:15:08 2022
CS61B: Lecture #14 7
public class C4 ...
void p(C1 x)
{ ... x.M ... }
The Access Rules: Protected
C1, C2, and C4 are distinct classes.
Class C2a is either class C2 itself or a subtype of C2.
package P1;
public class C1 ... {
// M is a method, field,...
protected int M ...
void h(C1 x)
{ ... x.M ... } // OK. }} ------------------------------ package P1;
package P2;
class C2 extends C1 {
void f(P1.C1 x) {... x.M ...} // ERROR // (x’s type is not subtype of C2.)
void g(C2a y) {... y.M ... } // OK
{... M ... } // OK (this.M)
Protected members of C1 are available within P1, as for package private. Outside P1, they are available within subtypes of C1 such as C2, but only if accessed from expressions whose static types are subtypes of C2.
Last modified: Tue Feb 15 15:15:08 2022
CS61B: Lecture #14 8
What May be Controlled
Classes and interfaces that are not nested may be public or package private.
Members—fields, methods, constructors, and (later) nested types—may have any of the four access levels.
May override a method only with one that has at least as permissive an access level. Reason: avoid inconsistency:
package P1; public class C1 {
public int f() { ... } }
public class C2 extends C1 {
// Actually a compiler error; pretend // it’s not and see what happens
int f() { ... }
package P2; class C3 {
void g(C2 y2) {
C1 y1 = y2
y2.f(); // Bad??? y1.f(); // OK??!!?
That is, there’s no point in restricting C2.f, because access control depends on static types, and C1.f is public.
Last modified: Tue Feb 15 15:15:08 2022 CS61B: Lecture #14 9
Intentions of this Design
public declarations represent specifications —what clients of a package are supposed to rely on.
package private declarations are part of the implementation of a
class that must be known to other classes that assist in the implementation.
protected declarations are part of the implementation that subtypes may need, but that clients of the subtypes generally won’t.
private declarations are part of the implementation of a class that only that class needs.
Last modified: Tue Feb 15 15:15:08 2022 CS61B: Lecture #14 10
package SomePack; public class A1 {
int f1() {
A1 a = ...
a.x1 = 3; // OK?
protected int y1;
private int x1;
// Anonymous package
class A2 {
void g(SomePack.A1 x) {
x.f1(); // OK?
x.y1 = 3; // OK? }
Quick Quiz
class B2 extends SomePack.A1 { void h(SomePack.A1 x) {
x.f1(); // OK?
x.y1 = 3; // OK?
Note: Last three lines of h have implicit this.’s in front. Static type of this is B2.
Last modified: Tue Feb 15 15:15:08 2022 CS61B: Lecture #14 11
package SomePack; public class A1 {
int f1() {
A1 a = ...
a.x1 = 3; // OK
protected int y1;
private int x1;
// Anonymous package
class A2 {
void g(SomePack.A1 x) {
x.f1(); // OK?
x.y1 = 3; // OK? }
Quick Quiz
class B2 extends SomePack.A1 { void h(SomePack.A1 x) {
x.f1(); // OK?
x.y1 = 3; // OK?
Note: Last three lines of h have implicit this.’s in front. Static type of this is B2.
Last modified: Tue Feb 15 15:15:08 2022 CS61B: Lecture #14 12
package SomePack; public class A1 {
int f1() {
A1 a = ...
a.x1 = 3; // OK
protected int y1;
private int x1;
// Anonymous package
class A2 {
void g(SomePack.A1 x) {
x.f1(); // ERROR
x.y1 = 3; // OK? }
Quick Quiz
class B2 extends SomePack.A1 { void h(SomePack.A1 x) {
x.f1(); // OK?
x.y1 = 3; // OK?
Note: Last three lines of h have implicit this.’s in front. Static type of this is B2.
Last modified: Tue Feb 15 15:15:08 2022 CS61B: Lecture #14 13
package SomePack; public class A1 {
int f1() {
A1 a = ...
a.x1 = 3; // OK
protected int y1;
private int x1;
// Anonymous package
class A2 {
void g(Some
程序代写 CS代考 加微信: powcoder QQ: 1823890830 Email: powcoder@163.com