Chapter 12 Inheritance and Exceptions Lecture Slides to Accompany An Introduction to Computer Science Using Java (2nd Edition) by S.N. Kamin, D. Mickunas,

Slides:



Advertisements
Similar presentations
ICS 201 Inheritance Introduction to Computer Science
Advertisements

JAVA: An Introduction to Problem Solving & Programming, 6 th Ed. By Walter Savitch ISBN © 2012 Pearson Education, Inc., Upper Saddle River,
Class Hierarchy (Inheritance)
Chapter 8Java: an Introduction to Computer Science & Programming - Walter Savitch 1 Chapter 8 l Basic Exception Handling »the mechanics of exceptions l.
JAVA: An Introduction to Problem Solving & Programming, 5 th Ed. By Walter Savitch and Frank Carrano. ISBN © 2008 Pearson Education, Inc., Upper.
Slides prepared by Rose Williams, Binghamton University ICS201 Exception Handling University of Hail College of Computer Science and Engineering Department.
1 Lecture 11 Interfaces and Exception Handling from Chapters 9 and 10.
Inheritance Inheritance Reserved word protected Reserved word super
1 More on Threads b b A section of code executed independently of other threads written within a single program. b b Java threads can access global data;
ITEC200 – Week03 Inheritance and Class Hierarchies.
Inheritance and Class Hierarchies Chapter 3. Chapter 3: Inheritance and Class Hierarchies2 Chapter Objectives To understand inheritance and how it facilitates.
1 Java - Threads A thread is an individual flow of control within a larger program. A program which is running more than one thread is said to be multithreaded.
Slides prepared by Rose Williams, Binghamton University Chapter 9 Exception Handling.
Liang, Introduction to Java Programming, Fifth Edition, (c) 2005 Pearson Education, Inc. All rights reserved Chapter 17 Exceptions and.
Exceptions in Java Fawzi Emad Chau-Wen Tseng Department of Computer Science University of Maryland, College Park.
© 2006 Pearson Addison-Wesley. All rights reserved4-1 Chapter 4 Data Abstraction: The Walls.
June 1, 2000 Object Oriented Programming in Java (95-707) Java Language Basics 1 Lecture 3 Object Oriented Programming in Java Language Basics Classes,
1 Chapter 6 Inheritance, Interfaces, and Abstract Classes.
Aalborg Media Lab 23-Jun-15 Inheritance Lecture 10 Chapter 8.
Slides prepared by Rose Williams, Binghamton University Chapter 9 More Exception Handling.
© 2006 Pearson Addison-Wesley. All rights reserved4-1 Chapter 4 Data Abstraction: The Walls.
Chapter 11: Handling Exceptions and Events J ava P rogramming: From Problem Analysis to Program Design, From Problem Analysis to Program Design, Fourth.
Chapter 10 Classes Continued
Introduction to Java Chapter 11 Error Handling. Motivations When a program runs into a runtime error, the program terminates abnormally. How can you handle.
1 Exception and Event Handling (Based on:Concepts of Programming Languages, 8 th edition, by Robert W. Sebesta, 2007)
Exceptions. Many problems in code are handled when the code is compiled, but not all Some are impossible to catch before the program is run  Must run.
Slides prepared by Rose Williams, Binghamton University ICS201 Lecture 9 : Exception Handling King Fahd University of Petroleum & Minerals College of Computer.
CIS 270—Application Development II Chapter 13—Exception Handling.
220 FINAL TEST REVIEW SESSION Omar Abdelwahab. INHERITANCE AND POLYMORPHISM Suppose you have a class FunClass with public methods show, tell, and smile.
CSM-Java Programming-I Spring,2005 Objects and Classes Overview Lesson - 1.
CMSC 202 Exceptions. Aug 7, Error Handling In the ideal world, all errors would occur when your code is compiled. That won’t happen. Errors which.
Java Programming: Guided Learning with Early Objects
More on Hierarchies 1. When an object of a subclass is instantiated, is memory allocated for only the data members of the subclass or also for the members.
Exceptions in Java. Exceptions An exception is an object describing an unusual or erroneous situation Exceptions are thrown by a program, and may be caught.
成都信息工程学院 计算机系 1 Java 程序设计 Java Programming Fall, 2010.
Data Structures Using Java1 Chapter 2 Inheritance and Exception Handling.
Chapter 3 Inheritance and Polymorphism Goals: 1.Superclasses and subclasses 2.Inheritance Hierarchy 3.Polymorphism 4.Type Compatibility 5.Abstract Classes.
Chapter 12 Handling Exceptions and Events. Chapter Objectives Learn what an exception is Become aware of the hierarchy of exception classes Learn about.
Summing Up Object Oriented Design. Four Major Components: Abstraction modeling real-life entities by essential information only Encapsulation clustering.
Computer Programming with JAVA Chapter 8. Exception Handling Basic Exception Handling the mechanics of exceptions Defining and Using Exceptions some "simple"
© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. Chapter 26 - Java Object-Based Programming Outline 26.1Introduction.
Introduction to Java Chapter 7 - Classes & Object-oriented Programming1 Chapter 7 Classes and Object-Oriented Programming.
Java Programming: From Problem Analysis to Program Design, 4e Chapter 11 Handling Exceptions and Events.
Chapter 5 Classes and Methods II Lecture Slides to Accompany An Introduction to Computer Science Using Java (2nd Edition) by S.N. Kamin, D. Mickunas, E.
Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All rights reserved Chapter 9 Inheritance and.
COP3502 Programming Fundamentals for CIS Majors 1 Instructor: Parisa Rashidi.
 In the java programming language, a keyword is one of 50 reserved words which have a predefined meaning in the language; because of this,
Coming up: Inheritance
JAVA INTRODUCTION. What is Java? 1. Java is a Pure Object – Oriented language 2. Java is developing by existing languages like C and C++. How Java Differs.
Inheritance and Class Hierarchies Chapter 3. Chapter 3: Inheritance and Class Hierarchies2 Chapter Objectives To understand inheritance and how it facilitates.
Inheritance and Class Hierarchies Chapter 3. Chapter Objectives  To understand inheritance and how it facilitates code reuse  To understand how Java.
Chapter 11: Advanced Inheritance Concepts. Objectives Create and use abstract classes Use dynamic method binding Create arrays of subclass objects Use.
Classes, Interfaces and Packages
1 Exceptions. 2 Syntax Errors, Runtime Errors, and Logic Errors syntax errors, runtime errors, and logic errors You learned that there are three categories.
Chapter 7 Classes and Methods III: Static Methods and Variables Lecture Slides to Accompany An Introduction to Computer Science Using Java (2nd Edition)
© 2006 Pearson Addison-Wesley. All rights reserved 1-1 Chapter 1 Review of Java Fundamentals.
Terms and Rules II Professor Evan Korth New York University (All rights reserved)
POLYMORPHISM Chapter 6. Chapter Polymorphism  Polymorphism concept  Abstract classes and methods  Method overriding  Concrete sub classes and.
Lecture10 Exception Handling Jaeki Song. Introduction Categories of errors –Compilation error The rules of language have not been followed –Runtime error.
And other languages…. must remember to check return value OR, must pass label/exception handler to every function Caller Function return status Caller.
Creating Java Applications (Software Development Life Cycle) 1. specify the problem requirements - clarify 2. analyze the problem - Input? Processes? Output.
Throw, Throws & Try-Catch Statements Explanations and Pictures from: Reference:
UMass Lowell Computer Science Java and Distributed Computing Prof. Karen Daniels Fall, 2000 Lecture 10 Java Fundamentals Objects/ClassesMethods.
Java Programming: Guided Learning with Early Objects Chapter 9 Inheritance and Polymorphism.
Programming With Java ICS201 University Of Ha’il1 ICS 201 Introduction to Computer Science Inheritance.
Inheritance and Polymorphism
Java Programming Language
Exception Handling Chapter 9 Edited by JJ.
CMSC 202 Exceptions.
Presentation transcript:

Chapter 12 Inheritance and Exceptions Lecture Slides to Accompany An Introduction to Computer Science Using Java (2nd Edition) by S.N. Kamin, D. Mickunas, E. Reingold

Chapter Preview In this chapter we will: show how to organize predefined classes using Java packages how access to methods and variables is controlled discuss the use of class inheritance to refine and extend classes refine our presentation on Java interfaces as a means of specifying object behavior show how programmer-defined exceptions are created, thrown and caught

Java Packages Application 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 folders The classes stored in each directory form a package The package names are formed by concatenating the directory names starting from a particular root directory

Some Predefined Java Packages Package NameContents java.appletClasses for implementing applets java.awtClasses for graphics, windows, and GUI’s java.awt.eventClasses supporting AWT event handling java.awt.imageClasses for image handling java.awt.peerInterface definitions s for platform independent graphical user interfaces (GUI’s) java.ioClasses for input and output java.langBasic language classes like Math (always available in any Java program) java.netClasses for networking java.utilUseful auxiliary classes like Date

Package Component Names Using a fully qualified component name x = java.lang.Math.sqrt(3); Using an import statement // to allow unqualified references to // all package classes import package.name.*; // to allow unqualified references to // a particular package class import package.name.class_name;

Import Examples This 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 abbreviated import java.util.date; Import java.awt.*; … Date d = new Date(); Point p = new Point(1,2); Button b = new Button();

Creating Your Own Packages Each package class must be stored in a file in an appropriately named directory The source code file for each package class must contain a package statement as its first non- commented statement package package_name; Several packages can be stored in the same directory Classes in different directories cannot be part of the same package

Visibility Rules and Packages Instance variables declared as public or private have the same visibility to classes in other packages Instance variables without explicitly declared visibility have package visibility Instance variables with package visibility are only visible to methods defined in classes belonging to the same package Similarly for static variables, instance methods, and static methods having package visibility Classes not explicitly declared public are not visible outside the package

Inheritance Allows 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 them The subclass can add variables, but cannot redefine them

Inheritance Example Class C is a subclass of class B (its superclass) if its declaration has the form class C extends B { … } The subclass is a specialization of the superclass The superclass is a generalization of the subclass

Inheritance and Messages When C is a subclass of B –C objects can respond to all messages that B objects can respond to –In general C objects can be used whenever B objects can be used It is possible the a subclass of B may have methods and variables that have not been defined in B –It is the case B objects may not always be used in place of C objects

Inheritance Hierarchy A class may have several subclasses and each subclass may have subclasses of its own The collection of all subclasses descended from a common ancestor is called an inheritance hierarchy The classes that appear below a given class in the inheritance hierarchy are its descendaents The classes that appear above a given class in the inheritance hierarchy are its ancestors

Inheritance and Visibility Rules Private variables and methods are not visible to subclasses or clients Public variables and methods are visible to all subclasses and clients Variables and methods with package visibility are only visible to subclasses and clients defined in the same package as the class A variable or method declared with the protected visibility modifier can only be referenced by subclasses of the class and no other classes

Visibility and Inheritance VisibilityPublicdefaultprotectedprivate Clients in same package CCCNone Clients in different packages CNone Subclass in same package C & R None Subclass in different package C & RNoneR Note: R is receiver; C is client

Overriding vs Overloading A method is overloaded if it has multiple definitions that are distinguished from one another by having different numbers or types of arguments A method is overridden when a subclass gives a different definition of the method with the same number and types of arguments

Constructors The 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 hierarchy If a superclass does not have a default constructor with no arguments, the subclass must explicitly call the superclass constructor with the appropriate arguments

Using super( ) Call Constructor The call to super must be the first statement in the subclass constructor Example: class C extends B { … public C ( … ) { super( B’s constructor arguments ); … } …

Calling Overridden Superclass Methods from Subclassess The 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 instead public void toString() { String result = super.toString(); return (result + “:” + second); }

Creation of Subclass Instances Assuming that PreciseClock is a subclass of the Clock class, the following is legal Clock dawn; dawn = new PreciseClock(3,45,30); The instance variable dawn will respond to all PreciseClock messages It is not legal to write this since Clock objects cannot respond to all PreciseClock messages PreciseClock dawn; dawn = new Clock(3,40);

Static and Dynamic Binding Static Binding –Determining which method will be invoked to respond to a message at compile time Dynamic Binding –Determining which method will be invoked to respond to a message at run time –Required when method definitions are overridden in subclasses, since type of the receiver class may not be known until run time

Abstract Classes Abstract classes are only used as super classes Classes are declared as abstract classes only if they will never be instantiated Abstract classes contain usually one or more abstract methods Example: public abstract class Mouse implements Direction { … abstract void makeMove( ); }

Abstract Methods Abstract methods have no body at all and just have their headers declared The only way to use an abstract class is to create a subclass that implements each abstract method Concrete classes are classes that implement each abstract method in their superclasses Example: abstract void makeMove( );

Exceptions Exceptions are things that are not supposed to occur Some exceptions (like division by zero) are avoidable through careful programming Some exceptions (like losing a network connection) are not avoidable or predictable Java allows programmers to define their own means of handling exceptions when they occur

Exception-Handling Mechanism 1.Mechanism for creating special exception classes (whose instances are called exception objects) 2.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 object 3.The statement try/catch allows the calling method to “catch” the “thrown” exception object and take appropriate actions

Exception Example The body of a method may call other methods as well as doing its own calculations Here the body of m will execute unless an out-of bounds exception occurs void m (){ try { … body of m … } catch (ArrayIndexOutOfBoundsException ae) { … code to recover from error … }

Control Flow and Exceptions When 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 exception It is possible for a catch statement to defer handling of an exception by including a throw statement of its own

Exception in p Handled by n void m() { … try { … n() … } catch (ArrayIndexOutOfBounds ae) { … } … } void n() { … try { … p() … } catch (ArrayIndexOutOfBounds ae) { … } … } void p() { … A[I] … }

Deferring Exception Handling to n’s Calling Method void n() { … try { … p() … } catch (ArrayIndexOutOfBounds ae) { if ( able to handle error ) handle it } else throw ae; } … }

finally Clause When exception is thrown control is transferred to method containing the catch block to handle the exception Control does not return to procedure in which the exception was thrown unless it contains a finally clause The finally clause can be used to clean up the programming environment after the exceptions has been handled

Finally clause Example void n() { … try { … open window … p() … } catch (SomeException se) { … } finally { … close window … } … } void p() { … throw se … }

Handling Multiple Exceptions void m() { … try { … n() … } catch (ArrayIndexOutOfBounds ae) { … } catch (NullPointerException npe) { … } … } void n() { try {… A[I] … anObject.v … } finally { … } … }

Exception Hierarchy Try can catch any exception using the following code try { … } 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 exception

Which handler is executed? In this example the second handler is never executed try { … } catch (Exception e) { … } catch (ArrayIndexOutOfBounds ae) { … } In this example the second handler is only executed if there is no array subscript error try { … } catch (ArrayIndexOutOfBounds ae) { … } catch (Exception e) { … }

Checked and Unchecked Exceptions Unchecked 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 exceptions

Programmer Defined Exceptions class InvalidIntegerException extends Exception { InvalidIntegerException (String s) { super(s); } InvalidIntegerException () { this(“”); }

Method Header Throws Clauses void m() { … try { … N() … } catch (InvalidIntegerException iie) { … } … } void n() throws InvalidIntegerException { … p() … } void p() throws InvalidIntegerException { … throw new InvalidIntegerException(); … }