Download - Interfaces, Arrays, Exceptions
CS 884 (Prasad) Java Interfaces 1
Interfaces, Arrays, Exceptions
Clone
Checked 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.
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.
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.
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.
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.
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); };
};
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.
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.
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
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]
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]
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]
CS 884 (Prasad) Java Interfaces 14
Arrays
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”};
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
CS 884 (Prasad) Java Interfaces 17
Cloning
Cf. copy constructor
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.
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.
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.
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.
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
}
}
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(); }}
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()); } } }
CS 884 (Prasad) Java Interfaces 25
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.
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.
CS 884 (Prasad) Java Interfaces 28
try { ...
throw new Exception(“test”);
...
} catch (InterruptedException e) { ...
} catch (Exception e) { ...
} finally { ...
}
Construct
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.
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)
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
CS 884 (Prasad) Java Interfaces 32
try { ... CallThatThrowsException(“TRY”); ... } finally { ... throw new Exception(“FINALLY”); }
try { ... return (“TRY”); ... } finally { ... return (“FINALLY”); }
Examples
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.
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.
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.
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)
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.
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.
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.
CS 884 (Prasad) Java Interfaces 40
RuntimeException• EmptyStackException
• ArithmeticException
• ArrayStoreException
• ClassCastException
• IllegalMonitorStateException
• NegativeArraySizeException
• NullPointerException
• SecurityException
CS 884 (Prasad) Java Interfaces 41
(Checked) Exception
• CloneNotSupportedException, NumberFormatException.
• IOException, InterruptedException, FileNotFoundException, EOFException.
• TooManyListenersException.
• AlreadyBoundException.
• User-defined Exceptions