You are on page 1of 116

SSD3: Object-Oriented Programming and

Design

Object-Oriented programming 1
Computer Programming Courses and Certificates

 SSD1 = Introduction to Information Systems


 SSD2 = Introduction to Computer Systems
 SSD3 = Object-Oriented Programming and Design
 SSD4 = User-Centered Design and Testing
 SSD5 = Data Structures and Algorithms

http://www.icarnegie.com/curriculum/curriculum
_home.html

Object-Oriented programming 2
Software Systems Development Courses and
Certificates

 SSD1 - 5 = Computer Programming courses and


certificate
 SSD6 = System-Level Programming
 SSD7 = Database Systems
 SSD8 = Networks and Distributed Programming
 SSD9 = Software Specification, Test and Maintenance
 SSD10 = Software Project Organization and
Management

Object-Oriented programming 3
Course Resource:
 My email address: ooaoodoop@gmail.com
 Web site for this course materials
http://www.icarnegie.com/
http://java.sun.com/
 Web site for this course information:
http://c4se.51.net/oop/index.htm
 Download site for this course resource:
ftp://www.isswhu.cn/ssd4/oop( ***** )
 Time for questioning and answering:
1.Before or after class
2.When do practice in lab
3.Other time (arrange before meet) and method (Email)

Object-Oriented programming 4
Lecture and practice arrangement
week content week content
1 Lecture 10 Lecture
2 Lecture 11 Practice/Exercise/Exa
3 Practice/Exercise 12 m
Lecture
4 Lecture 13 Practice/Exercise
5 Practice/Exercise 14 Lecture
6 Lecture 15 Practice/Exercise
7 Practice/Exercise/Exam 16 Lecture
8 Lecture 17 Practice/Exercise/Exa
9 Practice/Exercise 18 m
Lecture/Review

Object-Oriented programming 5
Overview ---- about our course
 Introducesstudents to problem solving by
means of object-oriented design and
implementation (实现,将设计思路写成代
码) .
 Emphasis on
 problem analysis
 solution design
 documentation
 implementation
 Programming in Java.
Object-Oriented programming 6
Three version of Java
 Java SE(Java platform, Standard Edition)
 Java EE(Java platform, Enterprise Edition)
 Java ME(Java platform, Micro Edition)

Object-Oriented programming 7

Object-Oriented programming 8
Course Organization
 The course is organized into 3 units.

 Unit 1.Class Design

 Unit 2. Class Implements

 Unit 3. Advanced Class Implements

Object-Oriented programming 9
Organization- exercises & exams
 Each unit consists of
a series of topics
 multiple-choice quizzes
 practical quizzes
 a few extended exercises

 Allwill help you gain a solid understanding of


the material.
 In addition, the course features some in-
class exams.
 Finally, we must pass the certificate exam
Object-Oriented programming 10
Text Book

Object-Oriented programming 11
Reference books
1 、 Bruce Eckel, Thinking in Java
 2 、 Harvey M.Deitel,Paul J.Deitel. Simply Java
Programming: An Application-Driven Tutorial
Approach
 3 、 Core Java 2, 6e, Volume I:Fundamentals
 4 、 Core Java 2, 5e, Volume II,Advanced
Features,
 5 、 Steven Haines,Stephen Potts, Java 2 Primer
Plus
 6 、陈烨 , 张蓓等 ,JDK 1.5 类库大全
 7 、 Harvey M.Deitel,Paul J.Deitel. Small Java How
to Program, Sixth Edition, 2005
Object-Oriented programming 12
Object-Oriented programming 13
Object-Oriented programming 14
Object-Oriented programming 15
Object-Oriented programming 16
Object-Oriented programming 17
Object-Oriented programming 18
System Requirements
 Java Platform, Standard Edition (JavaSE),
v6
 Instructions
on how to install J2SE are given in
Appendix B. Java 2 Platform, Standard Edition
(J2SE).
 Eclipse
3.2.1 and EclipseUML plug-in, or
another IDE with a debugger and an editor of
UML.
 Instructions
on how to install Eclipse and
EclipseUML are given in Appendix C. Eclipse.
Object-Oriented programming 19
Outcomes
 The purpose of SSD3 is for students to
 Learn to program using object-oriented
techniques.
 Learn to design robust( 健壮的 ), extensible
classes.
 Learn to express design using UML (统一建模
语言) .
 Learn to write programs by writing cooperating
classes and interfaces.

Object-Oriented programming 20
Students completing SSD3 will be able to

 I. Produce
 II. Use
 III. Knowledgeably Discuss
 IV. Hold Positions as Beginning Java
Programmer

Object-Oriented programming 21
I. Produce
 Java programs : exhibiting object-oriented
programming features including
 inheritance, polymorphism, abstract classes,
and interfaces
 Robust Java classes using exceptions and access
modifiers (访问限定符)
 Object Oriented Designs using UML
 Java implementation from a specification
 Extensions (扩展) to existing Java programs to
improve performance or to add functionality
 Professional quality code using code conventions
followed in the industry
Object-Oriented programming 22
II. Use
 Commonly used professional tools such as
debuggers, IDEs, and UML editors
 Utility classes and packages involving I/O, and
tokenization
 Java Swing classes to implement GUIs
 On-line resources for Java developments
 Design patterns
 Test cases for unit testing
 Collections( 集合 ) and iterators( 迭代器 )

Object-Oriented programming 23
III. Knowledgeably Discuss
 Advanced Object Oriented concepts

Object-Oriented programming 24
IV. Hold Positions as User Interface
Developers
 On successfully completing this course, the student
will be able to
 (a) execute programming tasks such as extending the
functionality of existing programs and improving the
performance of existing program modules
 (b) implement interactive GUIs (图形用户接口) in
Java,
 (c) implement classes that exhibit a specified behavior
 (d) debug and correct programs that do not perform
according to specification

Object-Oriented programming 25
Unit 1. Class Design

 1.1 Java Application


 1.2 Designing Classes

Object-Oriented programming 26
1.1 Java application
 Contents
 1.1.1 Applications in Java
 1.1.2 Using Eclipse
 1.1.3 Beginning with the Java API
 1.1.4 Console I/O
 1.1.5 Exception Objects
 1.1.6 Code Conventions
 1.1.7 Javadoc
 1.1.8 Debugging
 1.1.9 Debugging with Eclipse
 Assessments

Object-Oriented programming 27
1.1.1 Applications in Java

 Applets in Java
 Applications in Java

Object-Oriented programming 28
Applets in Java
 Java programs come in many forms:
 applets
 servlets
 applications.
 Applets
 referenced from web pages and
 interpreted by web browsers.
 Every applet contains a public class that extends the
class Applet.
 sample code(MyApplet.java) an applet that outputs
a message:
 Official demos

Object-Oriented programming 29
Applications in Java
 Javaapplications are “stand-alone”
programs (独立程序) , interpreted by
a Java interpreter on a host system
 not a web browser

Object-Oriented programming 30
How to start a java application

 How to execute a Java application?


 types a command invoking the Java interpreter
on the specified application.
Java ApplicationName -arguments
 The command java calls the Java interpreter and
ApplicationName is the name of the class that
will be executed.
 The operating system begins execution by
calling the method main() in the class
ApplicationName.
 demo

Object-Oriented programming 31
The method main in Applications

 Applications can consist of one or many classes;


 one of those classes must have a method main().
The method main() has the following signature.
 public static void main(String[] args)
 main() has one input parameter,
a String array that holds any command-line arguments
 User can specify when running.

 Users
can pass information to the application via
Command-line arguments

Object-Oriented programming 32
Some Code convention in Java Application
 Sample code (MyApplication.java) displaying
"This is my first application!" on the screen.
 The class containing method main() must be
public.
 The class declaration may or may not have
an extends - clause;
 applications differ from applets.

Object-Oriented programming 33
Code Convension
 Classnames should have the first character
of each word capitalized
 Should not contain any underscores ( _ ).
 E.g.,
WordCount ( correct, adheres to the convention,
whereas)
wordCount ( wrong )
wordcount ( wrong )
word_count ( wrong )
 Thefile containing the source code must
have the same name as the class it contains
and use the .java extension.
 E.g.,
the file containing the class WordCount
must be namedObject-Oriented
WordCount.java.
programming 34
1.1.2 Using IDE
 Integrated Development Environment (IDE)
 is a tool used by system developers to assist
them in the various phases of system
development.
 IDE for Java programming
 Eclipse (free open source)
 JBUILDER
 ……many, many
 You can choose your favourite one

Object-Oriented programming 35
IDE Function

 Create the Project


 Create the Class
 Compile the Class
 Execute the Application

Object-Oriented programming 36
1.1.3 Beginning with the Java API

 Introduction
 Packages and the import Statement
 The java.lang.String Class
 The java.util.StringTokenizer Class
 The Wrapper Classes

Object-Oriented programming 37
Introduction
 The Java Application Programming Interface
(API) represents an extensive Java library.
 These libraries are carefully written, robust
and extensively tested.

Object-Oriented programming 38
Javadoc tool

 The documentation for the Java API is


generated by the Javadoc tool.
 Javadoc produces a set of HTML pages from
the Javadoc comments in a Java source file.
 Javadoc comments an application's classes,
variables, and methods.
 users can use Javadoc comments in their
source code so the documentation for our
applications will have the same organization
and format as that of the Java API.

Object-Oriented programming 39
Packages and the import Statement

 Theclasses in the Java API are grouped into


packages.
 A package is simply a collection of related
classes. E.g., a package name:
java.util
 The fully qualified name of a class is
 [the
package name].[the class name], separated
by a dot. E.g.,
java.util.GregorianCalendar

Object-Oriented programming 40
two ways of declare object variables

 first : e.g.,
java.util.GregorianCalendar firstDate = new
java.util.GregorianCalendar(2004, 1, 1);
java.util.GregorianCalendar lastDate = new
java.util.GregorianCalendar(2004, 12, 31);
 second : e.g.,
import java.util.GregorianCalendar; //This statement
placed at the top of a file
GregorianCalendar firstDate = new
GregorianCalendar(2004, 1, 1);
GregorianCalendar lastDate = new
GregorianCalendar(2004, 12, 31);
Object-Oriented programming 41
two ways comparision
 first
 Typing the fully qualified name of a class is tedious and
the resulting code is difficult to read.
 second
 Java offers the import statement.
 used to "import" a class
 Or "import" an entire package of classes—into a file.

 An imported class can be referenced using its simple


name ( only class name), without the package name .
 An import statement consists of the keyword import, a
fully qualified name, and a semicolon:
 This is far more convenient, -- the package name needs
to be mentioned only once in the import statement.

Object-Oriented programming 42
Use * As Wildcard( 通配符 )
 whenuse several classes from the same
package. How to do?
 usingan import statement for each class? No!
 Imported the entire package!
import java.util.*;
 Theasterisk ( * ) acts as a wildcard,
representing all the classes in the specified
package.

Object-Oriented programming 43
The asterisk is convenient
 The asterisk is convenient. E.g.,
 While adding code uses the asterisk to import all the
classes in the package java.io but uses only one of them.
 New code that uses other classes in java.io can be
added without adding more import statements.
 Many programmers use the asterisk, even when
they need just one class in a package, because
 it is quick to type and it does not incur any overhead:
 importing a package does not slow compilation or
execution,
 it does not increase the size of the byte code.

Object-Oriented programming 44
not necessary to import java.lang

 The java.lang package is implicitly imported


into all Java applications.
 All applications can reference classes in the
java.lang package using their simple names.

Object-Oriented programming 45
How to become familiar with java APIs?

 Read API documentation


 Study methods and properties of classes.
 Study sample java code
 use them
 Practice makes perfect !

Object-Oriented programming 46
The java.lang.String Class

 Java provides no primitive string type


 the java.lang.String class is heavily used.
 Java does include the string literal
a sequence of characters within double quotes
e.g., "abc".
 A string literal is an instance of class String

Object-Oriented programming 47
some methods defined in class String
 String().
 Constructs a new String object that represents an empty
character sequence.
 String(char[] value).
 Constructs a new String object that represents the
sequence of characters contained in the character array.
 String(String original).
 Constructs a new String object that represents the same
sequence of characters as the argument.
 int size().
 Obtains the number of characters in the String.
 char charAt(int index).
 Returns the character at the specified index.

Object-Oriented programming 48
some methods defined in class String
 boolean equals(Object anObject).
 Returns true if the specified Object represents a String
with the same sequence of characters.
 int indexOf(int ch).
 Returns the index of the first occurrence of the character.
 int indexOf(String str).
 Returns the index of the first occurrence of the String.
 boolean startsWith(String prefix).
 Checks if the String has the specified prefix.
 Stringsubstring(int beginIndex, int endIndex).
Returns a substring.

Object-Oriented programming 49
String concatenation operator ( + )

 It is a binary operator( 双目运算符 ) that


requires two String operands.
 It concatenates these operands, returning
the result in a new String. E.g.,
 "one"+ "two“
 "onetwo"

 Notice that no separator is placed between


the operands in the result.
 two lines represent equivalent String objects

Object-Oriented programming 50
toString() method.
 Every class in the Java API has the method toString() .
 returns the String representation of an object.
 This means every instance of a Java API class has a String
equivalent:
"hello " + anyObject.toString()
 for convenience, if one of the operands to the concatenation
operator is an object (not a String, of course), that object‘s
toString() will be automatically invoked,
"hello " + anyObject instead of "hello " + anyObject.toString()
 When is a primitive type, it will be replaced by an equivalent
object and that object's toString method will be called. we
can write:
"hello " + 5 instead of "hello " + (new Integer(5)).toString()

Object-Oriented programming 51
toString() method (cont.)

 Notice:the plus symbol ( + ) is also used for


addition, at least one of its operands must be
a String for it to work as the concatenation
operator. E.g.,:
stdOut.println(2 + 3 + "5"); // prints 55, not 235
stdOut.println(2 + "" + 3 + "5"); // prints 235
"hello " + 5 ; // "hello " + (new Integer(5)).toString()

 sample code(StringClassDemo.java)

Object-Oriented programming 52
The java.util.StringTokenizer Class
 Tokenizing is the process of breaking a string
into smaller pieces called tokens( 标记 ).
 Tokens are separated, or delimited, by a
character or group of characters. E.g., using
white space(‘ ’) as the delimiter ( 分隔符 )
"This string has five tokens" the result will
be five tokens.

Object-Oriented programming 53
common delimiters
 White space (the most common delimiter (white
space includes the space character)
 the tab character( 制表符 \t)
 the newline character( 换行 \n)
 the carriage-return character( 回车 \r)
 and the form-feed character( 表格进入 \f)
 other popular delimiters include the underscore ( _ )
and the comma ( , ),E.g.,
 "This_string_has_five_tokens“
 "This,string,has,five,tokens"
 Any character can act as a delimiter. E.g., using "i"
 "Th“,"s str“,"ng has f" ,"ve tokens" four tokens
 choose a proper delimiter according to the program
requirement Object-Oriented programming 54
Methods of class StringTokenizer
 StringTokenizer(String str).
 Constructs a string tokenizer. The tokenizer uses the
default delimiter set, white space.
 StringTokenizer(String str, String delim).
 Constructs a string tokenizer. The argument delim
contains the character delimiters for separating tokens.
 boolean hasMoreTokens().
 Tests if there are more tokens to extract.
 String nextToken(String delim).
 Returns the next token in the string.
 int countTokens().
 Obtains the number of tokens left to be extracted, not the
number of tokens in the string.

Object-Oriented programming 55
Sample code use the class StringTokenizer

 Sample code (ProductInfo.java)


 Sample code
( StringTokenizerClassDemo.java )

Object-Oriented programming 56
The Wrapper Classes
 There are many classes in the Java API. And Programmers
can define many.
 but only a few primitives are available.
 In some respects, it would be nice if all data in Java
programs were treated in the same, consistent manner.
 Java offers classes that simulate the primitives. There is one
such class for each primitive. Together, these classes are
called the wrapper classes
java.lang.Byte java.lang.Short
java.lang.Integer java.lang.Long
java.lang.Character java.lang.Float
java.lang.Double java.lang.Boolean

Object-Oriented programming 57
The Wrapper Classes
 Notice : that names of the wrapper classes are very
similar to their primitive counterparts.
 A wrapper class contains a single field whose type
is the corresponding primitive. E.g.,
 the class Integer contains one field of type int.
 Sample code(WrapperConversion,java ) illustrates
the use of the Integer wrapper class.
 The application creates a wrapper object to store an
integer, and then it finds the equivalent long, double and
String value.
 The wrapper classes are a part of the package
java.lang do not need to be explicitly imported.
Object-Oriented programming 58
Primitives String objects
 The wrapper classes provide methods for
 converting primitives to String objects
 String objects to primitives
 E.g.,
 Integer.toString(10) converts the integer value 10 to the String "10",
 Integer.parseInt("10") converts the String "10" to the integer value 10.
 Sample code(ProductValue ) enhance the application
ProductInfo.
 The method nextToken() returns a String, which isn't very useful
when the token being extracted is a numeric value like quantity or
price.
 use the class Integer to convert the String containing the quantity to
an integer value;
 use the class Double to convert the String containing the price to a
double value.
 Now it is possible to compute the total value of the product.

Object-Oriented programming 59
1.1.4 Console I/O

 Thejava.io Package
 Reading Primitive Values

Object-Oriented programming 60
The java.io Package

 The class java.io.BufferedReader is used for input.


 The class java.io.PrintWriter is used for output.
 Sample code(AnyClassUsingIO.java ) as a
template for classes that use console I/O.
 Note :
 The private modifier prevents other classes from using
the variables stdIn, stdOut, and stdErr. This is just a
convention .
 makes it easy for programmers
 users to identify the different types of output.

Object-Oriented programming 61
System.in, System.out, System.err
 System.in
 the "standard" input stream.
 corresponds to keyboard input.
 System.out
 the "standard" output stream.
 corresponds to screen output.
 used to display typical and regular program
output.
 System.err
 the "error" output stream.
 corresponds to screen output.
 System.err is used to display prompts and error
messages. Object-Oriented programming 62
println and print method

 System.out and System.err could be used for


output directly.
 to wrap each in a PrintWriter object is more
convenient.
 The class PrintWriter has two printing methods:
println and print.
 printlnautomatically follows the output with a new line;
 print does not output with a new line;
 The methods println and print can take many types of
arguments.
 Sample code(PrintlnDemo.java)
Object-Oriented programming 63
automatic flushing 直接发送
 PrintWriter(OutputStream out, boolean autoFlush)
 Create a new PrintWriter from an existing OutputStream.
 boolean autoFlush indicates whether automatic
flushing should occur.
 When programs produce screen output, it does not
go directly to the screen. It goes to a holding area
called a buffer.
 When the buffer is full, it is automatically flushed.
 sends buffer contents to the screen.
 empties the buffer

Object-Oriented programming 64
automatic flushing
 most output statements do not fill the buffer so output sits in
the buffer instead of being displayed on the screen.
 Since programmers expect output to be displayed
immediately,
 the class PrintWriter has an optional, automatic flushing
feature called auto-flush.
 When the argument is true, auto-flush is enabled and the
buffer is automatically flushed after every call to method
println()
 but not after calls to method print().
 The programmer can use the method flush() to flush the
buffer after a call to method print().
 Sample code(Hello.java ) illustrates the use of
method flush.

Object-Oriented programming 65
Some explain of sample code
 Notice :
 the standard error output stream stdErr, is used to output prompts.
 If print() is not followed by flush(), the user will probably not see the
prompt right away. This is usually undesirable.
 System.in
 could be used for input directly.
 But it can only read one character at a time.
 Reading a line of input this way would be trouble. How to do?
 Wrapping System.in in a BufferedReader object
 makes it possible to read entire lines of input.
 The BufferedReader method to read an entire line is readLine().
 A call to method readLine() will
 Cause the program to wait, or block, until the user types a line of
information
 When the ENTER key pressed, the line is read by method readLine()
and returned as a String.

Object-Oriented programming 66
Reading Primitive Values
 Not all input is intended to be used as a String.
 Some program may be prompting for an integer,
how to do?
 An integer can be extracted from the input string
using a method in the wrapper class for integers.
int value = Integer.parseInt(stdIn.readLine());
 class Integer’s method parseInt() read a String
converted to an int
 Most wrapper classes have a similar parse method:
 class Double : parseDouble()
 class Float : parseFloat().
 class Boolean : getBoolean(), not parseBoolean()

Object-Oriented programming 67
extract a character from the input
 Two ways:
 1. Use the method charAt() to retrieve the
character in the String returned by method
readLine.
 2. Use the method read() instead of method
readLine(). But Notice:
read() will require a cast before the
assignment can be made because read()
returns an int, not a char
charTest = (char)
 Sample code (ReadThreeIntegers.java ) uses a
StringTokenizer object to read three integers from
one line of input
Object-Oriented programming 68
1.1.5 Exception Objects

 Exception Handling
 Exception Objects
 Exception Classes
 User-Defined Exceptions
 The try-catch Block
 The throws Clause
 The throw Statement
 Documenting Exceptions Using Javadoc

Object-Oriented programming 69
Exception Handling
 Robust code is code that responds appropriately to
 invalid inputs
 unexpected environmental conditions.
 E.g., try to open a file that does not exist or divide a number by zero
 Many failures or exceptional events—can occur that
interrupt the normal flow of a program.
 Robust code handles failures
 continuing execution despite the problem or
 terminating execution after displaying an error message.
 In traditional programming
 include conditional statements to detect and handle program
failures.
 this code is difficult to read and maintain.

Object-Oriented programming 70
Pseudo-code for Exception Analysis
 Pseudo-code for a method that reads an integer
from the standard input
int readInteger () {
Read a string from the standard input
Convert the string to an integer value
Return the integer value
}
 This pseudo-code ignores the failures
 The string cannot be read from the standard input.
 the standard input may be a damaged file.
 The string does not contain an integer.
 type "2r" instead of "25".

Object-Oriented programming 71
add code to detect / handle potential failures
int readInteger () {
while (true) {
read a string from the standard input;
if (read from the standard input fails) {
handle standard input error;
} else {
convert the string to an integer value;
if (the string does not contain an integer) {
handle invalid number format error;
} else {
return the integer value;
}
}
}
}
Object-Oriented programming 72
Exception handling mechanism

 Exception handling
 allows failures to be handled outside the normal
flow of the code.
 The resulting code is clear, easy to read, and
easy to maintain.
 With exception handling
 thenormal flow of the code is specified in the
body of a try block
 each failure is handled in a catch block
separated from the normal flow of the code.
Object-Oriented programming 73
pseudo-code that uses exception handling
int readInteger () {
while (true) {
try {
read a string from the standard input;
convert the string to an integer value;
return the integer value; }
catch (read from the standard input failed) {
handle standard input error;
}
catch (the string does not contain an integer){
handle invalid number format error;
}
}
}
Object-Oriented programming 74
Exception Objects

 In Java an exception is an object that


describes an abnormal situation.
 An exception object contains the following
information:
 The kind of exception
 A call stack( 调用栈 ) which indicates where the
exception occurred
 A string with additional information about the
exception

Object-Oriented programming 75
sequence of throwing exception

 sequence
 abnormal occurs  create exception object  throw it.
 If the calling method is not prepared to catch the
exception object, it throws to its calling method, and so
on.
 The exception object passes through the sequence of
methods that have been called (the call stack) until it is
caught.
 The method that catches the exception object uses the
information in the object to handle the exception.
 Samplecode (ExceptionDemo.java) for the
sequence of events illustrated figure on next page.
Object-Oriented programming 76
figure illustrates exception throwing and catching

Object-Oriented programming 77
ExceptionDemo analysis
 Calls:
 Main()  methodA()  methodB ()  methodC ()  methodD.
 methodD
 The last method in the sequence
 creates a new exception object
 throws it to methodC.
 The exception passes through
 methodD ()  methodC ()  methodB ()  methodA().
 methodA
 handles the exception by printing a stack trace
 terminating the program.
 The stack trace
 shows the sequence of methods that were called before the
exception was thrown.

Object-Oriented programming 78
NOTICE
 When a method throws an exception, none of the
remaining statements in that method are executed.
 If none of the methods in the call stack catch the
exception and the top-most method is main(), the
program displays a message in the standard error
stream( 错误输出流-显示器 ) to identifies the
exception and terminates.
 How to avoid termination of a program too early ?
 include try-catch blocks
 It enable the program to recover from failures.

Object-Oriented programming 79
information stored in the Exception object.

 The name of the exception:


 java.lang.Exception

 The exception message:


 This is an Exception Message
 The stack trace
 which is very helpful when debugging exceptions.
 It shows the sequence of methods that were called
before the exception was thrown.
 Notice
 theprint statements in methodB and methodC were
never executed. Why?
Object-Oriented programming 80
Exception objects’ methods
 String getMessage().
 Obtains the argument that was passed to the constructor
of the exception object.
 String toString().
 The name of the exception (its type), followed by a colon
( : ), followed by the String returned by method
getMessage().
 void printStackTrace().
 This method displays in the standard error stream,
 the String returned by method toString()
 followed by information that shows where the exception was
thrown, including a list of all the methods that were called before
the exception occurred.

Object-Oriented programming 81
Exception Classes

 Exception objects are instances of classes


that descend from class Throwable.
 Throwable has two subclasses: Error and
Exception.
 Class Error is used for serious problems from
which an application is unlikely to recover.
E.g., "out of memory" error.
 Class Exception is used for abnormal conditions
that an application can be expected to handled.

Object-Oriented programming 82
checked and unchecked exceptions
 Java divides exceptions in two categories:
 unchecked exceptions : Exceptions that are not
"checked" by the compiler
 checked exceptions : exceptions that are "checked" by
the compiler
 The compiler will not compile a file if
 itcontains a method where a checked exception may
occur and
 the method does not handle the checked exception in a
catch block or list it in the method header.
 Remember:
 The classes RuntimeException, Error and their
subclasses are unchecked exceptions.
 All other exception classes are checked exceptions.

Object-Oriented programming 83
Hierarchy of exceptions

Object-Oriented programming 84
User-Defined Exceptions

 A new checked exception class can be


defined by extending the class Exception;
 a new unchecked exception class can be
defined by extending the class
RuntimeException.
 Sample code(OutOfRangeException.java)
defines a checked exception for an out-of-
range error
 The second constructor is used when additional
information about the exception is available.

Object-Oriented programming 85
The try{ } catch{ } Block
 method uses try-catch block to handle an exception.
 try block encloses code that may throw an exception.
 A try block is followed by one or more catch blocks.
try {
// code that may throw exceptions
}
catch (ExceptionType1 e1) {
// code to handle the exception
}
catch (ExceptionType2 e2) {
// code to handle the exception
}
……

Object-Oriented programming 86
The try{ } catch{ } Block
 ExceptionType is the type or class name of
the exception that the catch block will
handle.
 Notice catch block looks like method header
because it has an argument.

Object-Oriented programming 87
Many catch blocks can appear after a try
block
 each catching a different exception. 不同异常做不
同处理
 When an exception is thrown, each catch block is
examined, starting with the catch block immediately
after the try block.
 When a match is found, the body of the matching
catch block is executed.
 Execution continue after the last catch block.
 If no matching catch block is found, the exception is
passed up the call stack
 Sample code( IntegerReader.java) has a method
called readInteger() that reads an integer from the
standard input
Object-Oriented programming 88
Code analysis of IntegerReader.java
 line 43 :
 BufferedReader.readLine() at might throw an
IOException.
 line 43 :
 The
method Integer.parseInt at might throw a
NumberFormatException.
 line 45 :
 The catch block handles the IOException by displaying,
in the standard error stream, the call stack and
terminating the program.
 line 50 :
 The catch block handles the NumberFormatException by
displaying, in the standard error stream, the message
"Invalid number format" and execution continues, that is,
the user is given another chance to enter an integer.
Object-Oriented programming 89
note
 Theargument of a catch block can be
misleading. E.g.,
 the following catch block will catch an IOException;
catch (IOException e) { // code to handle IOException,
FileNotFoundException, and EOFException }
 it will also catch
 a FileNotFoundException and
 an EOFException.
 Why? because the classes FileNotFoundException and
EOFException are subclasses of class IOException

Object-Oriented programming 90
The throws Clause
 If a checked exception might occur in a method and the
method does not have catch block to handle the checked
exception, then the checked exception must be declared in
the method header using a throws clause.
 E.g.,
 if an IOException might occur in readInteger() and readInteger()
doesn't handle it, then readInteger() must have the following header:
public int readInteger() throws IOException {
}
 If readInteger() does not list IOException in its throws clause,
compilation will fail with an error message about checked
exceptions.
 Unchecked exceptions may not be listed in a throws
clause,why?
 Because the compiler does not require it.

Object-Oriented programming 91
Sample code analysis

 sample code
(IntegerReaderThrowsException.java )
 neither
readInteger() nor main( ) catches
IOException so they both list IOException in their
throws clauses.
 When method main() throws an IOException
 the exception object is passed to the Java Virtual
Machine (JVM).
 The JVM displays the exception information and
terminates the program.
Object-Oriented programming 92
The throw Statement
 User-defined methods can also throw exceptions.
 How to? Use the keyword throw following by an exception
object.
throw new OutOfRangeException();
 The exception object is created like any other object, using
the new operator and a constructor.
throw new OutOfRangeException("Not a valid number");
 Sample code (PositiveInteger.java ) wraps a positive integer
value.
 It has a constructor, and methods to inspect and modify the positive
integer value.
 both the constructor and the setValue() create and throw an
OutOfRangeException when the value of the argument is not
positive (lines 59 and 86).
 Note that the OutOfRangeException is caught in method main at line
44.

Object-Oriented programming 93
Documenting Exceptions Using Javadoc
 The Javadoc tag for an exception is the @throws tag—the
@exception tag can also be used. The Javadoc comment
for a method should have a @throws tag for each checked
exception that the method might throw. It can also have
@throws tags for unchecked exceptions but this is not
necessary. The Javadoc comment should not have a
@throws tag for exceptions that are caught and handled by
the method.
 Use the following guidelines to document exceptions:
 When the method throws more than one exception, each exception
should be documented on a different line and should be listed
alphabetically.
 Place the @throws tags after the @param and @return tags.
 The @throws tags should describe the situation(s) that will cause the
exception.

Object-Oriented programming 94
1.1.6 Code Conventions
 Reference
 Code Conventions for the Java Programming Language.
 Contains the standard conventions that Sun Microsystems
follows and recommends that others follow. It covers
 file names
 file organization
 indentation
 comments
 declarations
 statements
 white space
 naming conventions
 programming practices
 Java Code Conventions Quick Reference.
Object-Oriented programming 95
Good programming style
 One of the objectives of this course is that you learn to use
good programming style.
 Good programming style is an important component of the
professional practice of software development.
 The product of your professional programming work will be your
source code. As any other commercial product, you should ensure
that your code has the highest quality.
 Your code will exist for a long time. You must ensure that your code
will be readable and easy to understand by others. Code that is
difficult to understand may be discarded and rewritten.
 As part of a developer team, you should strive for consistency
between your code and the code of your teammates.
 Your style of programming generally reflects the kind of programmer
that you are. Code that is clear and well organized usually reflects a
well-organized programmer with clear ideas.

Object-Oriented programming 96
A good style of programming makes the code
easier to trace, debug, and grade
 Basic principles of good style code :
 Code conventions should ensure that the logical structure
of the code is easy to follow.
 the statements in the body of a loop should be indented.
 Code conventions should improve readability.
 thename of identifiers should follow naming conventions so it is
easy to recognize constants, classes, methods, and variables.
 Code conventions should prevent the introduction of
accidental errors.
 braces should enclose the body of a loop even when the body
contains a single statement.
 This avoids the logical error that occurs when a programmer
adds a statement to the loop body without adding a set of braces.

Object-Oriented programming 97
When use conventions
 The choice of one set of conventions may seem
completely arbitrary.
 We choose to use Sun's code conventions because
they are recognized by an extensive community of
professional developers.
 On a final note, code conventions should not be
applied to your code after it is written.
 The name of a variable should follow the naming
convention when it is defined.
 A line of code should be properly indented when that line
is written.
 A control structure should never been written without
braces.

Object-Oriented programming 98
1.1.7 Javadoc

 Javadoc and the Javadoc Program


 Advice on Documenting
 Javadoc Syntax
 Reference Standard Java API Document

Object-Oriented programming 99
Javadoc and Javadoc Program
 Javadoc comments are
 written
by the programmer
 processed by the program Javadoc. – A tool
Software
Parses the Javadoc comments and the overall
structure of the program,
producing a set of HTML pages that serve as
documentation for the program.

Object-Oriented programming 100


Advice on Documenting
 To maintain software costs significantly more than
to develop it.
 The task of maintenance is far easier if the software
is well documented.
 When make document ?
 mistake : Many programmers will document a program
after it is finished.
 Documenting should be done in conjunction with coding.
 Using Javadoc
 enhances documentation.
 The documentation for the entire Java API is in Javadoc
format.

Object-Oriented programming 101


Javadoc Syntax
 Javadoc comments open with a "slash-asterisk-
asterisk" sequence ( /** ) and close with an
"asterisk-slash" sequence ( */ )
 E.g., The multi-line structure
/**
* body text
* body text
* body text
*/
 The single line structure
/** body text */
Object-Oriented programming 102
Javadoc tags
 Javadoc comments include Javadoc tags. Tag describes a particular attribute of
the entity being commented. Format : @TagName
 @author – programmer's name; used for classes
 @version – version of the program; used for classes
 @param – description of a formal parameter; used for methods and
constructors
 @return – description of a return value; used for methods
 @exception (or @throws) – description of an exception; used for
methods and constructors
 @see – reference to a related entity; used for classes, constructors,
methods, and data fields
 When several different tags are used in a Javadoc comment, they should
appear in the order illustrated above.
 Javadoc comments can contain HTML tags. Use HTML tags where appropriate.
 Sample code(TwoInts.java)
 Sample Document(TwoInts.htm)
Object-Oriented programming 103
the javadoc command
 javadoc
produce a collection of HTML pages
document classes

Object-Oriented programming 104


1.1.8 Debugging
 The Process of Debugging
 Print Statements
 The Debugger

Object-Oriented programming 105


The Process of Debugging
 Debugging is the process of identifying an error and
correcting it.
 Effective debugging does not come naturally.
 For many developers, debugging consumes an
enormous number of hours.
 The time needed to find an error and correct it will
depend on your proficiency in debugging.
 The use of specific strategies, like guessing, can waste
large amounts of time without obtaining any result.
 The process of identifying an error
 should be methodical
 it should not begin until the developer has a good
understanding of the program's code.

Object-Oriented programming 106


effective technique for debugging a program

Object-Oriented programming 107


Print Statements
 The use of print statements is a common
technique.
 It is available in many languages
 it is easy to implement.
 Be used to display important information

 This information may include:


 The called methods name
 The value of parameters
 The value of loop control variables
 The value of local variables
 The value of instance variables

 Sample code(SumCalculator.java) 108


Object-Oriented programming
Debugging result
 The application displays the method name, the method
arguments, and the values of the loop control variable
and the local variable total on each iteration of the loop.
 Note that this code does not have a bug.
 It just demonstrates how print statements can be used
to trace the execution of a program.

Object-Oriented programming 109


The Debugger
 Trouble of using print statements
 Insert them , and delete then after debugging
 A debugger is a convenient tool for locating the
source of errors.
 A debugger allows you to execute one line at a time
and observe the effect on the program's variables.
 There are several types of Java debuggers
available:
 Integrated development environments (IDEs), such as
Eclipse, Sun ONE Studio, Borland JBuilder, and BlueJ,
contain their own debuggers.
 Stand-alone graphical debuggers, such as JSwat and
DDD
 Text-based debuggers, such as Sun jdb

Object-Oriented programming 110


Debuggers’ capabilities:
 Setting breakpoints.
 A breakpoint is a marker to stop the execution of the
program before executing a statement.
 Stepping through a program. Once program stop, the debugger
provides the following set of commands to continue the
execution.
 resume. Continue with the execution, not single stepping.
 step into.
 step over.
 step return.
 Examine the data.
 The debugger can display the values of the variables in the
current method and class. the user can "open" the object
and inspect the value of each element.
 Stack trace.
 When a breakpoint is hit and execution is suspended, the
debugger can display the sequence of called methods.
Object-Oriented programming 111
Note of debugger
 A debugger is a powerful tool for monitoring
the execution of a program and identifying
the source of errors.
 But a debugger is only a tool.
 The ability to identify and eliminate errors
ultimately depends on the proficiency of the
programmer.

Object-Oriented programming 112


1.1.9 Debugging with Eclipse
 Introduction
 The Example
 Create the Project
 Import Class Employee
 Execute the Application
 Show Line Numbers
 Debug the Class
 Place a Breakpoint
 Monitor the Execution
 Diagnostic and Fix the Error

Object-Oriented programming 113


Introduction
 Thissection will demonstrate the debugging
process using a debugger.
 We use the debugger included in Eclipse.
 The basic functions provided by this
debugger are similar to other debuggers.
 You can also walk through this tutorial with
another debugger, e.g., JBuilder

Object-Oriented programming 114


The Example
 Sample code (Employee.java )

Object-Oriented programming 115


Assessments
 Practical Quiz 1
 Practical Quiz 2
 Multiple-Choice Quiz 1
 Exercise 1

Object-Oriented programming 116

You might also like