interfaces, arrays, exceptions

41
CS 884 (Prasad) Java Interfaces 1 Interfaces, Arrays, Exceptions Clone Checked Exceptions

Upload: finna

Post on 19-Jan-2016

48 views

Category:

Documents


0 download

DESCRIPTION

Interfaces, Arrays, Exceptions. Clone Checked Exceptions. Interface. An interface is an abstract class. Implicitly: Members are public . Fields are final and static (with initializers). Methods are abstract . Behavior may be informally specified. - PowerPoint PPT Presentation

TRANSCRIPT

Page 1: Interfaces, Arrays, Exceptions

CS 884 (Prasad) Java Interfaces 1

Interfaces, Arrays, Exceptions

Clone

Checked Exceptions

Page 2: Interfaces, Arrays, Exceptions

CS 884 (Prasad) Java Interfaces 2

Interface• An interface is an abstract class. Implicitly:

– Members are public.– Fields are final and static (with initializers).– Methods are abstract.

• Behavior may be informally specified.• Java supports single inheritance of classes

(fields and methods), but multiple inheritance of interfaces (constants and method signatures).

• An interface can extend another interface.• A class can implement an interface.

Page 3: Interfaces, Arrays, Exceptions

CS 884 (Prasad) Java Interfaces 3

Multiple Inheritance : Pros and Cons

• Tree-structured class hierarchy leads to needless

code duplication when several abstractions are

specializations of other orthogonal abstractions.

• Independent sets of classes {A,B} and

{C,D} can result in four new classes using

multiple inheritance. In contrast, single

inheritance requires four new class

definitions by copying.

Page 4: Interfaces, Arrays, Exceptions

CS 884 (Prasad) Java Interfaces 4

(cont’d)• DAG class structure facilitates code sharing

and reduces code duplication.• Unfortunately:

– There is no uniform application-independent way to deal with repeated inheritance of fields in diamond net. (To share or to duplicate?)

– There is no uniform strategy to resolve method conflicts or to combine method impls.

– Reuse of source code possible, but not object code.

Page 5: Interfaces, Arrays, Exceptions

CS 884 (Prasad) Java Interfaces 5

Java Design Decisions

• Simplify the language (compiler) by banning multiple inheritance of classes.

• Support multiple inheritance of interfaces (to share method signatures and to document behavior).

• Code duplication can be minimized by approximating multiple inheritance using composition and delegation.

Page 6: Interfaces, Arrays, Exceptions

CS 884 (Prasad) Java Interfaces 6

(cont’d)

• From orthogonal classes {A,B} and {C,D}, generate subclasses AC (AD, BC, BD).

• These extend A (A, B, B) with a new field of type C (D, C, D).

• Then, delegate the call to a method in C (D, C, D) on objects of class AC (AD, BC, BD) to the new field.

Page 7: Interfaces, Arrays, Exceptions

CS 884 (Prasad) Java Interfaces 7

class C extends A, B {…}

class A { ... }; interface IB { ...

T bm(Fs) { ... };

};

class B implements IB { …

T bm(Fs) { ... };

};

class C extends A implements IB { …

B b;

T bm { b.bm(Vs); };

};

Page 8: Interfaces, Arrays, Exceptions

CS 884 (Prasad) Java Interfaces 8

Role of Interfaces in Java• Defining Scalar types (a la C++) in Java 1.4 and before

• Improves Readability but not Reliability. (Cf. Ada)– Java 5 natively supports Enumerated types

• Enables integration of multiple implementations of an abstract data type.

• Polymorphic data in arrays; Dynamic binding.• Serves as a type parameter.

– (Cf. Ada Generics, C++ Templates, ML’s Functors, etc)

• In AWT, it provides a convenient, abstract and reliable means for connecting event generating graphical/widget objects to application dependent event handlers.

Page 9: Interfaces, Arrays, Exceptions

CS 884 (Prasad) Java Interfaces 9

(cont’d)• Multiple Inheritance of interfaces facilitates

approximating multiple inheritance of classes for minimizing code duplication. This involves defining a field for each “parent” class and explicitly maintaining consistency among its fields and dispatching each method incorporating conflict resolution strategies.

Page 10: Interfaces, Arrays, Exceptions

CS 884 (Prasad) Java Interfaces 10

interface I { Vector v = new Vector(); int i = 5;}interface J extends I { Vector w = (Vector) v.clone(); int i = 10; int j = i; }class Interface implements J {

public static void main(String [] args) {// I.v = J.w; ERROR

System.out.println(" i = " + i + " j = " + j ); I.v.addElement(new Integer(44));

System.out.println(" w = " + w + " v = " + v); System.out.println(" Hidden I.i = " + I.i);}

}

i = 10 j = 10 w = [44] v = [44]

Hidden I.i = 5

Page 11: Interfaces, Arrays, Exceptions

CS 884 (Prasad) Java Interfaces 11

interface I { Vector v = new Vector(); String i = “ABC”;}interface J extends I { Vector w = (Vector) v.clone(); String i = new String(“pqr ”); String j = i + “+ XYZ”;}

class InterfaceVectorString implements J {public static void main(String [] args) { System.out.println(" Hidden I.i = " + I.i);

// compile-time constant – no interface initializationSystem.out.println(" i = " + i + " j = " + j );// J initialized after ISystem.out.println(" w = " + w + " v = " + v);

I.v.addElement(new Integer(55)); System.out.println(" w = " + w + " v = " + v);}

} Hidden I.i = ABC i = pqr j = pqr + XYZ w = [] v = [] w = [] v = [55]

Page 12: Interfaces, Arrays, Exceptions

CS 884 (Prasad) Java Interfaces 12

interface I { Vector v = new Vector(); String i = “ABC”;}interface J extends I { Vector w = (Vector) v.clone(); String i = “PQR ”; String j = i + “+ XYZ”;}

class InterfaceVectorString1 implements J {public static void main(String [] args) { System.out.println(" Hidden I.i = " + I.i);

System.out.println(" i = " + i + " j = " + j ); // compile-time constant – no interface initialization

I.v.addElement(new Integer(55)); System.out.println(" w = " + w + " v = " + v);

// J initialized after I}

} Hidden I.i = ABC i = PQR j = PQR + XYZ w = [55] v = [55]

Page 13: Interfaces, Arrays, Exceptions

CS 884 (Prasad) Java Interfaces 13

interface I { Vector v = new Vector(); String i = “ABC”;}interface J extends I { Vector w = (Vector) v.clone(); String i = new String(“pqr ”); String j = i + “+ XYZ”;}

class InterfaceVectorString2 implements J {public static void main(String [] args) { System.out.println(" Hidden I.i = " + I.i);

// compile-time constant – no interface initializationSystem.out.println(" i = " + i + " j = " + j );// J initialized after I; I’s value is NOT a compile-time constant

I.v.addElement(new Integer(55)); System.out.println(" w = " + w + " v = " + v);}

} Hidden I.i = ABC i = pqr j = pqr + XYZ w = [] v = [55]

Page 14: Interfaces, Arrays, Exceptions

CS 884 (Prasad) Java Interfaces 14

Arrays

Page 15: Interfaces, Arrays, Exceptions

CS 884 (Prasad) Java Interfaces 15

Arrays

• An array object contains a number of variables accessed using a non-negative integer index.

• Array Type and Array Variable• int [] [] twoD;

• String items [];

• Array Creation and Initialization• int [] [] twoD = { {1,2}, null };

• String [] items = {“abc”};

Page 16: Interfaces, Arrays, Exceptions

CS 884 (Prasad) Java Interfaces 16

Array Members• public final length;

• number of elements in the array.

• public Object clone () { ... }• creates a new array object and then initializes its

elements from the “source” array. • copying is shallow, not recursive.

– int [] ia1 = {1,2,3};– int [] ia2 = (int []) ia1.clone();

– Cf. Assignment: ia1 = ia2;– Array indices checked at run-time. (ArrayStoreException)– Cf. Ada Unconstrained array types

Page 17: Interfaces, Arrays, Exceptions

CS 884 (Prasad) Java Interfaces 17

Cloning

Cf. copy constructor

Page 18: Interfaces, Arrays, Exceptions

CS 884 (Prasad) Java Interfaces 18

Cloning public class Object { ...

protected Object clone() throws CloneNotSupportedException { ... }

…} public interface Cloneable { }

• clone() method creates an object from another object of the same type.

• Direct instances of class Object cannot be cloned.

• Cloneable is a marker interface.

Page 19: Interfaces, Arrays, Exceptions

CS 884 (Prasad) Java Interfaces 19

(cont’d)

A class may

• support clone, by defining a public clone and implementing Cloneable.

• conditionally support clone, if “contents” support it. (Collection classes)

• allow subclasses to support clone. (E.g., Object)

• forbid clone by throwing CloneNotSupportedException.

Page 20: Interfaces, Arrays, Exceptions

CS 884 (Prasad) Java Interfaces 20

class A { protected Object clone() throws CloneNotSupportedException { return super.clone(); //assume a new defn }}class B { public Integer b = new Integer(5);

public Object clone() throws CloneNotSupportedException { return super.clone(); }}

• Cannot clone both A- and B-objects.• Subclasses of B must declare clone public.• Used for appropriate clone for descendents.

Page 21: Interfaces, Arrays, Exceptions

CS 884 (Prasad) Java Interfaces 21

class C extends B implements Cloneable { public Integer c = new Integer(6);

public Object clone() throws CloneNotSupportedException { return super.clone(); }}

• Supports clone but descendents can throw exception.

class D extends C { public Object clone() { try { return super.clone(); } catch (CloneNotSupportedException e){} }}

• Descendents must support public clone that does not throw any exception.

Page 22: Interfaces, Arrays, Exceptions

CS 884 (Prasad) Java Interfaces 22

class TestClone {

public static void main(String [] args)

throws CloneNotSupportedException {

new Object() . clone(); // compile-time error

new A() . clone(); // run-time error

new B() . clone(); // run-time error

C cobj = new C(); C cobjc = cobj.clone();

System.out.println( “C: “ + (cobj == cobjc));

// C: false

D dobj = new D(); D dobjc = dobj.clone();

System.out.println( “D: “ + (dobj = dobjc));

// D: D@f3a655dd

}

}

Page 23: Interfaces, Arrays, Exceptions

CS 884 (Prasad) Java Interfaces 23

Recursive types (Cf. Expanded types)

class Problem { Problem p = new Problem()}class Infinite { public static void main(String[] args) { new Problem(); }}

Page 24: Interfaces, Arrays, Exceptions

CS 884 (Prasad) Java Interfaces 24

Deep Clone? public class IntStack implements Cloneable { private int[] buf; private int top; public IntStack(int max) { buf = new int[max]; top = -1; } public Object clone() { try { IntStack is = (IntStack) super.clone(); is.buf = (int[]) buf.clone(); return is; } catch (CloneNotSupportedException e){ throw new InternalError(e.toString()); } } }

Page 25: Interfaces, Arrays, Exceptions

CS 884 (Prasad) Java Interfaces 25

Exceptions

Page 26: Interfaces, Arrays, Exceptions

CS 884 (Prasad) Java Interfaces 26

• Compiler checks syntax, and flags type mismatches, uninitialized variables, etc.

• Semantic constraints of the language or applications can be violated at run-time.

Instead of aborting a program, or exhibiting arbitrary behavior when such violations occur, the exception mechanism enables “graceful degradation”, enhancing portability and robustness.

Page 27: Interfaces, Arrays, Exceptions

CS 884 (Prasad) Java Interfaces 27

The causes of exceptions in Java

• An abnormal execution condition was synchronously detected by JVM.

• Java semantics violation.

• Error in linking/loading of a program.

• Exceeding resource limitations.

• A throw-statement (user-defined exception) was executed.

• An asynchronous exception occurred as• Thread.stop() was invoked.

• An internal error occurred in JVM.

Page 28: Interfaces, Arrays, Exceptions

CS 884 (Prasad) Java Interfaces 28

try { ...

throw new Exception(“test”);

...

} catch (InterruptedException e) { ...

} catch (Exception e) { ...

} finally { ...

}

Construct

Page 29: Interfaces, Arrays, Exceptions

CS 884 (Prasad) Java Interfaces 29

• Exceptions are well-integrated into the class hierarchy.

• When an exception is thrown, control is transferred to the nearest dynamically enclosing catch-clause of a try-statement that handles the exception.

• Context-sensitive handling

• catch-clauses are ordered using “exception specificity”.

• An exception thrown by the finally-block is propagated in preference to an exception thrown by the try-block.

Page 30: Interfaces, Arrays, Exceptions

CS 884 (Prasad) Java Interfaces 30

1. class Exp1 {2. public static void main(String[] args) throws Exception{3. try {4. throw new Exception("Throw Exception");5. } catch (Exception e) {6. throw e;7. throw new Exception("REThrown Exception");8. }9. finally { throw new Exception("FINALLY"); }10. }11. }

No Exception

Exception in thread "main" java.lang.Exception: Throw Exception at Exp1.main(Exp1.java:4) Exception in thread "main" java.lang.Exception: REThrown Exception at Exp1.main(Exp1.java:7)Exception in thread "main" java.lang.Exception: FINALLY

at Exp1.main(Exp1.java:9)

Page 31: Interfaces, Arrays, Exceptions

CS 884 (Prasad) Java Interfaces 31

class Exp2 {static String f() {

try { throw(new Exception());

return("first-try");} catch (Exception e) {

return("second-catch"); } finally {

return("third-finally");}

} public static void main(String[] args) {

System.out.println(f()); }}

first-try//return(first-try) unreachablesecond-catch third-finally

Page 32: Interfaces, Arrays, Exceptions

CS 884 (Prasad) Java Interfaces 32

try { ... CallThatThrowsException(“TRY”); ... } finally { ... throw new Exception(“FINALLY”); }

try { ... return (“TRY”); ... } finally { ... return (“FINALLY”); }

Examples

Page 33: Interfaces, Arrays, Exceptions

CS 884 (Prasad) Java Interfaces 33

Exception Handlers• Pinpoint location/cause of problem (in a layered

software). Record information for debugging.• Give diagnostic message, and take corrective or

alternate action. • In a real-time system, this may be turning-on

fault indicator lights to turning-off devices.• Restore environment to a well-defined state.

• Release resources (locks), save files, etc.

Page 34: Interfaces, Arrays, Exceptions

CS 884 (Prasad) Java Interfaces 34

Exceptions vs Error codesChecking and Returning error code to signal abnormal condition is

unsuitable because:

• Error handling code and normal processing code mixed up.

• A “caller” can ignore error code.

• Not conducive to portability and robustness.

• Difficult to pinpoint source/location of abnormality from results that are only indirectly related to it.

• For a sequence of nested calls, the intermediate procedures must explicitly check and propagate codes.

– Using global variable or gotos is not appropriate either.

– In Java, the compiler guarantees that checked exceptions are always handled, and the JVM takes care of propagating exceptions using the call-stack.

Page 35: Interfaces, Arrays, Exceptions

CS 884 (Prasad) Java Interfaces 35

Java Errors and Exceptions

• Subclasses of class Throwable – Error

• unchecked: recovery difficult or impossible– Exception (language defined + user-defined)

• unchecked: too complex for compiler guarantees; too cumbersome for programmer to declare/handle. (logic errors)

• checked : requires programmer to provide an exception handler or propagate exception explicitly.

Page 36: Interfaces, Arrays, Exceptions

cs480 (Prasad) L10Exceptions 36

class Exp { void p() { q(1); } int q(int x) { return 1/(x - x); }

public static void main(String[] args) { (new Exp()).p(); } }

>java Exp

java.lang.ArithmeticException:

/ by zero

at Exp.q(Exp.java:3)

at Exp.p(Exp.java:2)

at Exp.main(Exp.java:6)

Page 37: Interfaces, Arrays, Exceptions

cs480 (Prasad) L10Exceptions 37

class MyExp extends Exception { }class TestExp3 { static void p() throws MyExp { throw new MyExp(); } public static void main(String [] args)

throws MyExp { p(); }}

• Checked Exception is explicitly propagated by main.

Page 38: Interfaces, Arrays, Exceptions

cs480 (Prasad) L10Exceptions 38

class MyExp extends Exception { }class TestExp4 { static void p() throws MyExp { throw new MyExp(); } public static void main(String [] args){

try {

p();

} catch (MyExp e) {}; }}

• Checked Exception is explicitly handled in main.

Page 39: Interfaces, Arrays, Exceptions

CS 884 (Prasad) Java Interfaces 39

Errors

• Loading: ClassFormatError, ClassCircularityError,

NoClassDefFoundError.

• Linking: IllegalAccessError,InstantantiationError,

NoSuchField, NoSuchMethodError.

• Verification: VerifyError.

• Initialization: ExceptionInInitializerError.

• Resource: InternalError, OutOfMemoryError,

StackOverflowError, UnknownError.

Page 40: Interfaces, Arrays, Exceptions

CS 884 (Prasad) Java Interfaces 40

RuntimeException• EmptyStackException

• ArithmeticException

• ArrayStoreException

• ClassCastException

• IllegalMonitorStateException

• NegativeArraySizeException

• NullPointerException

• SecurityException

Page 41: Interfaces, Arrays, Exceptions

CS 884 (Prasad) Java Interfaces 41

(Checked) Exception

• CloneNotSupportedException, NumberFormatException.

• IOException, InterruptedException, FileNotFoundException, EOFException.

• TooManyListenersException.

• AlreadyBoundException.

• User-defined Exceptions