Bài giảng An Introduction to Computer Science Using Java - Chapter 12 Inheritance and Exceptions

Tài liệu Bài giảng An Introduction to Computer Science Using Java - Chapter 12 Inheritance and Exceptions: Chapter 12 Inheritance and ExceptionsLecture Slides to AccompanyAn Introduction to Computer Science Using Java (2nd Edition)byS.N. Kamin, D. Mickunas, E. ReingoldChapter PreviewIn this chapter we will:show how to organize predefined classes using Java packageshow access to methods and variables is controlleddiscuss the use of class inheritance to refine and extend classesrefine our presentation on Java interfaces as a means of specifying object behaviorshow how programmer-defined exceptions are created, thrown and caughtJava PackagesApplication programmer interface (API)All classes provided to programmers along with the Java compiler (e.g. Math or MouseEvent)Java expects to find these classes in separate directories or foldersThe classes stored in each directory form a packageThe package names are formed by concatenating the directory names starting from a particular root directorySome Predefined Java PackagesPackage NameContentsjava.appletClasses for implementing appletsjava.awtClasse...

ppt39 trang | Chia sẻ: honghanh66 | Lượt xem: 693 | Lượt tải: 0download
Bạn đang xem trước 20 trang mẫu tài liệu Bài giảng An Introduction to Computer Science Using Java - Chapter 12 Inheritance and Exceptions, để tải tài liệu gốc về máy bạn click vào nút DOWNLOAD ở trên
Chapter 12 Inheritance and ExceptionsLecture Slides to AccompanyAn Introduction to Computer Science Using Java (2nd Edition)byS.N. Kamin, D. Mickunas, E. ReingoldChapter PreviewIn this chapter we will:show how to organize predefined classes using Java packageshow access to methods and variables is controlleddiscuss the use of class inheritance to refine and extend classesrefine our presentation on Java interfaces as a means of specifying object behaviorshow how programmer-defined exceptions are created, thrown and caughtJava PackagesApplication programmer interface (API)All classes provided to programmers along with the Java compiler (e.g. Math or MouseEvent)Java expects to find these classes in separate directories or foldersThe classes stored in each directory form a packageThe package names are formed by concatenating the directory names starting from a particular root directorySome Predefined Java PackagesPackage NameContentsjava.appletClasses for implementing appletsjava.awtClasses for graphics, windows, and GUI’sjava.awt.eventClasses supporting AWT event handlingjava.awt.imageClasses for image handlingjava.awt.peerInterface definitions s for platform independent graphical user interfaces (GUI’s)java.ioClasses for input and outputjava.langBasic language classes like Math (always available in any Java program)java.netClasses for networkingjava.utilUseful auxiliary classes like DatePackage Component NamesUsing a fully qualified component namex = java.lang.Math.sqrt(3);Using an import statement// to allow unqualified references to// all package classesimport package.name.*;// to allow unqualified references to// a particular package classimport package.name.class_name; Import ExamplesThis code java.util.Date d = new java.util.Date();java.awt.Point p = new java.awt.Point(1,2);java.awt.Button b = new java.awt.Button(); Can be abbreviatedimport java.util.date;Import java.awt.*;Date d = new Date();Point p = new Point(1,2);Button b = new Button();Creating Your Own PackagesEach package class must be stored in a file in an appropriately named directoryThe source code file for each package class must contain a package statement as its first non-commented statementpackage package_name;Several packages can be stored in the same directoryClasses in different directories cannot be part of the same packageVisibility Rules and PackagesInstance variables declared as public or private have the same visibility to classes in other packagesInstance variables without explicitly declared visibility have package visibilityInstance variables with package visibility are only visible to methods defined in classes belonging to the same packageSimilarly for static variables, instance methods, and static methods having package visibilityClasses not explicitly declared public are not visible outside the package InheritanceAllows programmers to customize a class for a specific purpose, without actually modifying the original class (the superclass)The derived class (subclass) is allowed to add methods or redefine themThe subclass can add variables, but cannot redefine themInheritance ExampleClass C is a subclass of class B (its superclass) if its declaration has the formclass C extends B { }The subclass is a specialization of the superclassThe superclass is a generalization of the subclassInheritance and MessagesWhen C is a subclass of BC objects can respond to all messages that B objects can respond toIn general C objects can be used whenever B objects can be usedIt is possible the a subclass of B may have methods and variables that have not been defined in BIt is the case B objects may not always be used in place of C objectsInheritance HierarchyA class may have several subclasses and each subclass may have subclasses of its ownThe collection of all subclasses descended from a common ancestor is called an inheritance hierarchyThe classes that appear below a given class in the inheritance hierarchy are its descendaentsThe classes that appear above a given class in the inheritance hierarchy are its ancestorsInheritance and Visibility RulesPrivate variables and methods are not visible to subclasses or clientsPublic variables and methods are visible to all subclasses and clientsVariables and methods with package visibility are only visible to subclasses and clients defined in the same package as the classA variable or method declared with the protected visibility modifier can only be referenced by subclasses of the class and no other classesVisibility and InheritanceVisibilityPublicdefaultprotectedprivateClients in same packageCCCNoneClients in different packagesCNoneNoneNoneSubclass in samepackageC & RC & RC & RNoneSubclass in different packageC & RNoneRNoneNote: R is receiver; C is clientOverriding vs OverloadingA method is overloaded if it has multiple definitions that are distinguished from one another by having different numbers or types of argumentsA method is overridden when a subclass gives a different definition of the method with the same number and types of arguments ConstructorsThe general rule is that when a subclass is created Java will call the superclass constructor first and then call the subclass constructors in the order determined by the inheritance hierarchyIf a superclass does not have a default constructor with no arguments, the subclass must explicitly call the superclass constructor with the appropriate argumentsUsing super( ) Call ConstructorThe call to super must be the first statement in the subclass constructorExample:class C extends B { public C ( ) { super( B’s constructor arguments ); } Calling Overridden Superclass Methods from SubclassessThe following code generates an infinite loop because toString( ) is interpreted as this.toString( )public void toString() { String result = toString(); return (result + “:” + second);}To make a call toString in the superclass insteadpublic void toString() { String result = super.toString(); return (result + “:” + second);}Creation of Subclass InstancesAssuming that PreciseClock is a subclass of the Clock class, the following is legalClock dawn;dawn = new PreciseClock(3,45,30);The instance variable dawn will respond to all PreciseClock messagesIt is not legal to write this since Clock objects cannot respond to all PreciseClock messagesPreciseClock dawn;dawn = new Clock(3,40); Static and Dynamic BindingStatic BindingDetermining which method will be invoked to respond to a message at compile timeDynamic BindingDetermining which method will be invoked to respond to a message at run timeRequired when method definitions are overridden in subclasses, since type of the receiver class may not be known until run timeAbstract ClassesAbstract classes are only used as super classesClasses are declared as abstract classes only if they will never be instantiatedAbstract classes contain usually one or more abstract methodsExample:public abstract class Mouse implements Direction { abstract void makeMove( );}Abstract MethodsAbstract methods have no body at all and just have their headers declaredThe only way to use an abstract class is to create a subclass that implements each abstract methodConcrete classes are classes that implement each abstract method in their superclassesExample:abstract void makeMove( );ExceptionsExceptions are things that are not supposed to occurSome exceptions (like division by zero) are avoidable through careful programmingSome exceptions (like losing a network connection) are not avoidable or predictableJava allows programmers to define their own means of handling exceptions when they occur Exception-Handling MechanismMechanism for creating special exception classes (whose instances are called exception objects)The statement throw e is used to signal the occurrence of an exception and return control to the calling method and e refers to an exception objectThe statement try/catch allows the calling method to “catch” the “thrown” exception object and take appropriate actions Exception ExampleThe body of a method may call other methods as well as doing its own calculationsHere the body of m will execute unless an out-of bounds exception occursvoid m (){ try { body of m } catch (ArrayIndexOutOfBoundsException ae) { code to recover from error } }Control Flow and ExceptionsWhen exception is thrown control returns through the methods called in reverse calling order until a try statement is found with a catch block for the exceptionIt is possible for a catch statement to defer handling of an exception by including a throw statement of its ownException in p Handled by nvoid m() { try { n() } catch (ArrayIndexOutOfBounds ae) { } }void n() { try { p() } catch (ArrayIndexOutOfBounds ae) { } }void p() { A[I] }Deferring Exception Handling to n’s Calling Methodvoid n() { try { p() } catch (ArrayIndexOutOfBounds ae) { if ( able to handle error ) handle it } else throw ae; } }finally ClauseWhen exception is thrown control is transferred to method containing the catch block to handle the exceptionControl does not return to procedure in which the exception was thrown unless it contains a finally clauseThe finally clause can be used to clean up the programming environment after the exceptions has been handledFinally clause Examplevoid n() { try { open window p() } catch (SomeException se) { } finally { close window } }void p() { throw se }Handling Multiple Exceptionsvoid m() { try { n() } catch (ArrayIndexOutOfBounds ae) { } catch (NullPointerException npe) { } }void n() { try { A[I] anObject.v } finally { }}Exception HierarchyTry can catch any exception using the following codetry { }catch (Exception e) { handle any type of exception }You must be careful because Java executes the first catch statement it finds that capable of handling the exceptionWhich handler is executed?In this example the second handler is never executedtry { }catch (Exception e) { }catch (ArrayIndexOutOfBounds ae) { }In this example the second handler is only executed if there is no array subscript errortry { }catch (ArrayIndexOutOfBounds ae) { }catch (Exception e) { }Checked and Unchecked ExceptionsUnchecked exceptions do not have to be handled (e.g. ArrayIndexOutOfBounds or NullPointer)Checked exceptions must be handled when they occur Most programmer defined exceptions are for checked exceptionsProgrammer Defined Exceptionsclass InvalidIntegerException extends Exception { InvalidIntegerException (String s) { super(s); } InvalidIntegerException () { this(“”); }} Method Header Throws Clausesvoid m() { try { N() } catch (InvalidIntegerException iie) { } }void n() throws InvalidIntegerException { p() }void p() throws InvalidIntegerException { throw new InvalidIntegerException(); }

Các file đính kèm theo tài liệu này:

  • pptchapter12_4777.ppt
Tài liệu liên quan