Interfaces, Arrays, Exceptions - PowerPoint PPT Presentation

About This Presentation
Title:

Interfaces, Arrays, Exceptions

Description:

... for appropriate clone for descendents. CS 884 (Prasad) Java ... Descendents must support public clone that does not throw any exception. CS 884 (Prasad) ... – PowerPoint PPT presentation

Number of Views:19
Avg rating:3.0/5.0
Slides: 42
Provided by: TKPr6
Learn more at: http://cecs.wright.edu
Category:

less

Transcript and Presenter's Notes

Title: Interfaces, Arrays, Exceptions


1
Interfaces, Arrays, Exceptions
  • Clone
  • Checked Exceptions

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.

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.

4
(contd)
  • 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.

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.

6
(contd)
  • 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.

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)

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, MLs Functors,
    etc)
  • In AWT, it provides a convenient, abstract and
    reliable means for connecting event generating
    graphical/widget objects to application dependent
    event handlers.

9
(contd)
  • 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.

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

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
    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)

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

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
    initialization
  • System.out.println(" i " i " j " j
    )
  • // J initialized after I Is value is NOT a
    compile-time constant
  • I.v.addElement(new Integer(55))
  • System.out.println(" w " w " v "
    v)

14
Arrays
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

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

17
Cloning
  • Cf. copy constructor

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.

19
(contd)
  • 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 CloneNotSupportedExceptio
    n.

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.

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.

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_at_f3a655dd

23
Recursive types (Cf. Expanded types)
  • class Problem
  • Problem p new Problem()
  • class Infinite
  • public static void main(String args)
  • new Problem()

24
Deep Clone?
  • public class IntStack implements Cloneable
  • private int buf
  • private int top
  • public IntStack(int max)
  • buf new intmax 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())

25
Exceptions
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.

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.

28
Construct
  • try ...
  • throw new Exception(test)
  • ...
  • catch (InterruptedException e) ...
  • catch (Exception e) ...
  • finally ...

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.

30
  • 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.java4)
  • Exception in thread "main" java.lang.Exception
    REThrown Exception
  • at Exp1.main(Exp1.java7)
  • Exception in thread "main" java.lang.Exception
    FINALLY
  • at Exp1.main(Exp1.java9)

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) unreachable
  • second-catch

32
Examples
  • try ...
  • CallThatThrowsException(TRY)
    ...
  • finally ...
  • throw new
    Exception(FINALLY)
  • try ...
  • return (TRY) ...
  • finally ...
  • return
    (FINALLY)

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.

34
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 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.

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.

36
  • class Exp
  • void p() q(1)
  • int q(int x) return 1/(x - x)
  • public static void main(String args)
  • (new Exp()).p()
  • gtjava Exp
  • java.lang.ArithmeticException
  • / by zero
  • at Exp.q(Exp.java3)
  • at Exp.p(Exp.java2)
  • at Exp.main(Exp.java6)

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.

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.

39
Errors
  • Loading ClassFormatError, ClassCircularityError,
    NoClassDefFoundError.
  • Linking IllegalAccessError,InstantantiationError,
    NoSuchField, NoSuchMethodError.
  • Verification VerifyError.
  • Initialization ExceptionInInitializerError.
  • Resource InternalError, OutOfMemoryError,
    StackOverflowError, UnknownError.

40
RuntimeException
  • EmptyStackException
  • ArithmeticException
  • ArrayStoreException
  • ClassCastException
  • IllegalMonitorStateException
  • NegativeArraySizeException
  • NullPointerException
  • SecurityException

41
(Checked) Exception
  • CloneNotSupportedException, NumberFormatException.
  • IOException, InterruptedException,
    FileNotFoundException, EOFException.
  • TooManyListenersException.
  • AlreadyBoundException.
  • User-defined Exceptions
Write a Comment
User Comments (0)
About PowerShow.com