410 likes | 544 Views
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.
E N D
Interfaces, Arrays, Exceptions Clone Checked Exceptions Java Interfaces
Interface • An interface is anabstractclass. Implicitly: • Members arepublic. • Fields arefinalandstatic (with initializers). • Methods areabstract. • 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. Java Interfaces
Multiple Inheritance : ProsandCons • Tree-structured class hierarchyleads 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 definitionsby copying. Java Interfaces
(cont’d) • DAG class structurefacilitates 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. Java Interfaces
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. Java Interfaces
(cont’d) • From orthogonal classes{A,B}and{C,D},generate subclassesAC (AD, BC, BD). • TheseextendA (A, B, B)with anew fieldof typeC (D, C, D). • Then,delegatethe call to a method inC (D, C, D)on objects of classAC (AD, BC, BD)to the new field. Java Interfaces
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); }; }; Java Interfaces
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. Java Interfaces
(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. Java Interfaces
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 Java Interfaces
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 initialization System.out.println(" i = " + i + " j = " + j ); // J initialized after I System.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] Java Interfaces
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] Java Interfaces
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 initialization System.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] Java Interfaces
Arrays Java Interfaces
Arrays • An array object contains a number of variables accessed using a non-negative integer index. • Array Type and Array Variable • int [] []twoD; • Stringitems[]; • Array Creation and Initialization • int [] []twoD = { {1,2}, null }; • String []items = {“abc”}; Java Interfaces
Array Members • publicfinallength; • number of elements in the array. • publicObjectclone () { ... } • creates a new array object and then initializes its elements from the “source” array. • copying isshallow, 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 Java Interfaces
Cloning Cf. copy constructor Java Interfaces
Cloning publicclassObject{ ... protectedObjectclone() throwsCloneNotSupportedException { ... } … } public interfaceCloneable{ } • clone() method creates an object from another object of the same type. • Direct instances of classObject cannot be cloned. • Cloneable is a marker interface. Java Interfaces
(cont’d) A class may • supportclone, by defining a publiccloneandimplementing Cloneable. • conditionally supportclone, if “contents” support it. (Collection classes) • allow subclasses to supportclone. (E.g., Object) • forbidclone by throwingCloneNotSupportedException. Java Interfaces
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. Java Interfaces
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. Java Interfaces
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 } } Java Interfaces
Recursive types (Cf. Expanded types) class Problem { Problem p = new Problem() } class Infinite { public static void main(String[] args) { new Problem(); } } Java Interfaces
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()); } } } Java Interfaces
Exceptions Java Interfaces
Compiler checkssyntax, and flagstype mismatches, uninitialized variables, etc. • Semantic constraints of thelanguageorapplicationscanbe 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. Java Interfaces
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. Java Interfaces
Construct try{ ... throw newException(“test”); ... }catch(InterruptedExceptione) { ... }catch(Exceptione) { ... }finally{ ... } Java Interfaces
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. Java Interfaces
class Exp1 { • public static void main(String[] args) throws Exception{ • try { • throw new Exception("Throw Exception"); • } catch (Exception e) { • throw e; • throw new Exception("REThrown Exception"); • } • finally { throw new Exception("FINALLY"); } • } • } 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) Java Interfaces
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) unreachable second-catch third-finally Java Interfaces
Examples try{ ... CallThatThrowsException(“TRY”); ... }finally{ ... throw newException(“FINALLY”); } try{ ... return (“TRY”); ... }finally{ ... return (“FINALLY”); } Java Interfaces
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. Java Interfaces
Exceptions vs Error codes Checking and Returning error code to signal abnormal condition is unsuitable because: • Error handling code and normal processing code mixed up. • A “caller” can ignoreerror 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. Java Interfaces
Java Errors and Exceptions • Subclasses ofclassThrowable • 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 exceptionexplicitly. Java Interfaces
class Exp { void p() { q(1); } int q(int x) { return 1/(x - x); } public static void main(String[] args) { (new Exp()).p(); } } >javaExp java.lang.ArithmeticException: / by zero at Exp.q(Exp.java:3) at Exp.p(Exp.java:2) at Exp.main(Exp.java:6) L10Exceptions
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. L10Exceptions
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. L10Exceptions
Errors • Loading: ClassFormatError, ClassCircularityError, NoClassDefFoundError. • Linking: IllegalAccessError,InstantantiationError, NoSuchField, NoSuchMethodError. • Verification: VerifyError. • Initialization: ExceptionInInitializerError. • Resource: InternalError, OutOfMemoryError, StackOverflowError, UnknownError. Java Interfaces
RuntimeException • EmptyStackException • ArithmeticException • ArrayStoreException • ClassCastException • IllegalMonitorStateException • NegativeArraySizeException • NullPointerException • SecurityException Java Interfaces
(Checked) Exception • CloneNotSupportedException, NumberFormatException. • IOException, InterruptedException, FileNotFoundException, EOFException. • TooManyListenersException. • AlreadyBoundException. • User-defined Exceptions Java Interfaces