123
Object-Oriented Object-Oriented programming programming 1 SSD3: Object-Oriented SSD3: Object-Oriented Programming and Design Programming and Design

Object-Oriented programming 1 SSD3: Object-Oriented Programming and Design

Embed Size (px)

Citation preview

Page 1: Object-Oriented programming 1 SSD3: Object-Oriented Programming and Design

Object-Oriented programmingObject-Oriented programming 11

SSD3: Object-Oriented Programming and SSD3: Object-Oriented Programming and Design Design

Page 2: Object-Oriented programming 1 SSD3: Object-Oriented Programming and Design

Object-Oriented programmingObject-Oriented programming 22

Computer Programming Courses and CertificatesComputer 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

Page 3: Object-Oriented programming 1 SSD3: Object-Oriented Programming and Design

Object-Oriented programmingObject-Oriented programming 33

Software Systems Development Courses and Software Systems Development Courses and CertificatesCertificates

SSD1 - 5 = Computer Programming courses and certificate

SSD6 = System-Level ProgrammingSSD7 = Database SystemsSSD8 = Networks and Distributed ProgrammingSSD9 = Software Specification, Test and MaintenanceSSD10 = Software Project Organization and

Management

Page 4: Object-Oriented programming 1 SSD3: Object-Oriented Programming and Design

Object-Oriented programmingObject-Oriented programming 44

Overview ---- about our courseOverview ---- about our course Introduces students to problem solving by

means of object-oriented design and implementation (实现,将设计思路写成代码) .

Emphasis on problem analysissolution designdocumentation implementation

Programming in Java.

Page 5: Object-Oriented programming 1 SSD3: Object-Oriented Programming and Design

Object-Oriented programmingObject-Oriented programming 55

Three version of JavaThree version of JavaJava SE(Java platform, Standard Edition)Java EE(Java platform, Enterprise Edition)Java ME(Java platform, Micro Edition)

Page 6: Object-Oriented programming 1 SSD3: Object-Oriented Programming and Design

Object-Oriented programmingObject-Oriented programming 66

Page 7: Object-Oriented programming 1 SSD3: Object-Oriented Programming and Design

Object-Oriented programmingObject-Oriented programming 77

Course OrganizationCourse OrganizationThe course is organized into 3 units.

Unit 1.Class Design

Unit 2. Class Implements

Unit 3. Advanced Class Implements

Page 8: Object-Oriented programming 1 SSD3: Object-Oriented Programming and Design

Object-Oriented programmingObject-Oriented programming 88

Organization- exercises & examsOrganization- exercises & examsEach unit consists of

a series of topics multiple-choice quizzes practical quizzesa few extended exercises

All will help you gain a solid understanding of the material.

In addition, the course features some in-class exams.

Finally, we must pass the final exam

Page 9: Object-Oriented programming 1 SSD3: Object-Oriented Programming and Design

Object-Oriented programmingObject-Oriented programming 99

Text BookText Book

Page 10: Object-Oriented programming 1 SSD3: Object-Oriented Programming and Design

Object-Oriented programmingObject-Oriented programming 1111

Page 11: Object-Oriented programming 1 SSD3: Object-Oriented Programming and Design

Object-Oriented programmingObject-Oriented programming 1212

Page 12: Object-Oriented programming 1 SSD3: Object-Oriented Programming and Design

Object-Oriented programmingObject-Oriented programming 1313

Page 13: Object-Oriented programming 1 SSD3: Object-Oriented Programming and Design

Object-Oriented programmingObject-Oriented programming 1414

Page 14: Object-Oriented programming 1 SSD3: Object-Oriented Programming and Design

Object-Oriented programmingObject-Oriented programming 1515

Page 15: Object-Oriented programming 1 SSD3: Object-Oriented Programming and Design

Object-Oriented programmingObject-Oriented programming 1616

System Requirements System Requirements Java Platform, Standard Edition (JavaSE), v6

Instructions on how to install J2SE are given in Appendix B.

Eclipse and EclipseUML plug-inor another IDE with a debugger and an editor

of UML. Instructions on how to install Eclipse and

EclipseUML are given in Appendix C. Eclipse.

Page 16: Object-Oriented programming 1 SSD3: Object-Oriented Programming and Design

Object-Oriented programmingObject-Oriented programming 1717

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

Page 17: Object-Oriented programming 1 SSD3: Object-Oriented Programming and Design

Object-Oriented programmingObject-Oriented programming 1818

Students completing SSD3 will be able toStudents completing SSD3 will be able to

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

Programmer

Page 18: Object-Oriented programming 1 SSD3: Object-Oriented Programming and Design

Object-Oriented programmingObject-Oriented programming 1919

I. ProduceI. 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

Page 19: Object-Oriented programming 1 SSD3: Object-Oriented Programming and Design

Object-Oriented programmingObject-Oriented programming 2020

II. UseII. 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( 迭代器 )

Page 20: Object-Oriented programming 1 SSD3: Object-Oriented Programming and Design

Object-Oriented programmingObject-Oriented programming 2121

III. Knowledgeably Discuss III. Knowledgeably Discuss Advanced Object Oriented concepts

Page 21: Object-Oriented programming 1 SSD3: Object-Oriented Programming and Design

Object-Oriented programmingObject-Oriented programming 2222

IV. Hold Positions as User Interface IV. Hold Positions as User Interface DevelopersDevelopers

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

Page 22: Object-Oriented programming 1 SSD3: Object-Oriented Programming and Design

Object-Oriented programmingObject-Oriented programming 2323

1.1  Java Application 1.2  Designing Classes

Unit 1.  Class DesignUnit 1.  Class Design

xqw
w1 1st 仅做了些介绍第二周开始讲ssd3正文
Page 23: Object-Oriented programming 1 SSD3: Object-Oriented Programming and Design

Object-Oriented programmingObject-Oriented programming 2424

1.1 Java application1.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

Page 24: Object-Oriented programming 1 SSD3: Object-Oriented Programming and Design

Object-Oriented programmingObject-Oriented programming 2525

11.1.1 Applications in Java .1.1 Applications in Java

Applets in Java Applications in Java

Page 25: Object-Oriented programming 1 SSD3: Object-Oriented Programming and Design

Object-Oriented programmingObject-Oriented programming 2626

Applets in JavaApplets in Java Java programs come in many forms:

applications applets Servlets Midlet ……

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

xqw
w21st
Page 26: Object-Oriented programming 1 SSD3: Object-Oriented Programming and Design

Object-Oriented programmingObject-Oriented programming 2727

Applications in Java Applications in Java Java applications are “stand-alone” programs

(独立应用程序) , interpreted by a Java interpreter on a host systemnot a web browser 无需依赖浏览器运行

Page 27: Object-Oriented programming 1 SSD3: Object-Oriented Programming and Design

Object-Oriented programmingObject-Oriented programming 2828

How to start a java applicationHow to start a java applicationHow 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.arguments

The operating system begins execution by calling the method main() in the class ApplicationName.

demo

Page 28: Object-Oriented programming 1 SSD3: Object-Oriented Programming and Design

Object-Oriented programmingObject-Oriented programming 2929

The method main in ApplicationsThe 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

Page 29: Object-Oriented programming 1 SSD3: Object-Oriented Programming and Design

Object-Oriented programmingObject-Oriented programming 3030

Sample codeSample 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.

Page 30: Object-Oriented programming 1 SSD3: Object-Oriented Programming and Design

Object-Oriented programmingObject-Oriented programming 3131

Some Code convention in Java ApplicationSome Code convention in Java ApplicationClass names should have the first character

of each word capitalizedShould not contain any underscores ( _ ). E.g.,

WordCount ( correct, adheres to the convention, whereas)

wordCount ( wrong ) wordcount ( wrong ) word_count ( wrong )

The file 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 named WordCount.java.

Page 31: Object-Oriented programming 1 SSD3: Object-Oriented Programming and Design

Object-Oriented programmingObject-Oriented programming 3232

1.1.2 Using IDE1.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 programmingEclipse (free open source)NETBAENJBUILDER……many, many You can choose your favourite one

Page 32: Object-Oriented programming 1 SSD3: Object-Oriented Programming and Design

Object-Oriented programmingObject-Oriented programming 3333

IDE FunctionIDE Function

Create the Project Create the PackageCreate the Class Compile the Class Execute the Application

Page 33: Object-Oriented programming 1 SSD3: Object-Oriented Programming and Design

Object-Oriented programmingObject-Oriented programming 3434

1.1.3 Beginning with the Java API 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

Page 34: Object-Oriented programming 1 SSD3: Object-Oriented Programming and Design

Object-Oriented programmingObject-Oriented programming 3535

IntroductionIntroduction The Java Application Programming Interface

(API) represents an extensive Java library(可扩展的 java 程序库) .

These libraries are carefully written, robust and extensively tested. (健壮且被广泛的测试过)

Page 35: Object-Oriented programming 1 SSD3: Object-Oriented Programming and Design

Object-Oriented programmingObject-Oriented programming 3636

Javadoc toolJavadoc toolThe documentation (文档) for the Java

API is generated by the Javadoc tool. Javadoc produces a set of HTML pages from

the Javadoc comments ( javadoc 注释) in a Java source file ( java 源文件) .

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.

Page 36: Object-Oriented programming 1 SSD3: Object-Oriented Programming and Design

Object-Oriented programmingObject-Oriented programming 3737

Packages and the import StatementPackages and the import Statement

The classes 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

Page 37: Object-Oriented programming 1 SSD3: Object-Oriented Programming and Design

Object-Oriented programmingObject-Oriented programming 3838

two ways of declare object variables 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);

Page 38: Object-Oriented programming 1 SSD3: Object-Oriented Programming and Design

Object-Oriented programmingObject-Oriented programming 3939

two ways of declare object variables two ways of declare object variables

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

Page 39: Object-Oriented programming 1 SSD3: Object-Oriented Programming and Design

Object-Oriented programmingObject-Oriented programming 4040

two ways comparision 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.

Page 40: Object-Oriented programming 1 SSD3: Object-Oriented Programming and Design

Object-Oriented programmingObject-Oriented programming 4141

Use Use ** As Wildcard ( As Wildcard ( 通配符通配符 ))when use several classes from the same

package. How to do?using an import statement for each class? No! Imported the entire package!

import java.util.*; The asterisk ( * ) acts as a wildcard,

representing all the classes in the specified package.

Page 41: Object-Oriented programming 1 SSD3: Object-Oriented Programming and Design

Object-Oriented programmingObject-Oriented programming 4242

The asterisk is convenientThe 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.

Page 42: Object-Oriented programming 1 SSD3: Object-Oriented Programming and Design

Object-Oriented programmingObject-Oriented programming 4343

not necessary to import java.langnot 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.

Page 43: Object-Oriented programming 1 SSD3: Object-Oriented Programming and Design

Object-Oriented programmingObject-Oriented programming 4444

How to become familiar with java APIs?How to become familiar with java APIs?

Read API documentation Study methods and properties of classes. Study sample java codeuse themPractice makes perfect !

Page 44: Object-Oriented programming 1 SSD3: Object-Oriented Programming and Design

Object-Oriented programmingObject-Oriented programming 4545

The java.lang.String Class 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

xqw
w3
Page 45: Object-Oriented programming 1 SSD3: Object-Oriented Programming and Design

Object-Oriented programmingObject-Oriented programming 4646

some methods defined in class Stringsome 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.

Page 46: Object-Oriented programming 1 SSD3: Object-Oriented Programming and Design

Object-Oriented programmingObject-Oriented programming 4747

some methods defined in class Stringsome 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.

String substring(int beginIndex, int endIndex) 取子串 Returns a substring.

Page 47: Object-Oriented programming 1 SSD3: Object-Oriented Programming and Design

Object-Oriented programmingObject-Oriented programming 4848

String concatenation operator (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.

Important : two lines represent equivalent String objects see demo StringTest.java

Page 48: Object-Oriented programming 1 SSD3: Object-Oriented Programming and Design

Object-Oriented programmingObject-Oriented programming 4949

toString() method.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()

Page 49: Object-Oriented programming 1 SSD3: Object-Oriented Programming and Design

Object-Oriented programmingObject-Oriented programming 5050

toString() method.toString() method.

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, 自动给调用 toString() 方法"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() will be called. we can write:

"hello " + 5 instead of "hello " + (new Integer(5)).toString()

Page 50: Object-Oriented programming 1 SSD3: Object-Oriented Programming and Design

Object-Oriented programmingObject-Oriented programming 5151

toString() method (cont.)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)

Page 51: Object-Oriented programming 1 SSD3: Object-Oriented Programming and Design

Object-Oriented programmingObject-Oriented programming 5252

The java.util.StringTokenizer ClassThe java.util.StringTokenizer ClassTokenizing 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.

Page 52: Object-Oriented programming 1 SSD3: Object-Oriented Programming and Design

Object-Oriented programmingObject-Oriented programming 5353

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

Page 53: Object-Oriented programming 1 SSD3: Object-Oriented Programming and Design

Object-Oriented programmingObject-Oriented programming 5454

other popular delimitersother 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

tokensnote

choose a proper delimiter according to the program requirement

Page 54: Object-Oriented programming 1 SSD3: Object-Oriented Programming and Design

Object-Oriented programmingObject-Oriented programming 5555

Methods of class StringTokenizer 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. 注意返回的是剩下的标记数量,不是该字符串总的标记数量

Page 55: Object-Oriented programming 1 SSD3: Object-Oriented Programming and Design

Object-Oriented programmingObject-Oriented programming 5656

Sample code use the class StringTokenizer Sample code use the class StringTokenizer

Sample code (ProductInfo.java)Sample code

( StringTokenizerClassDemo.java )

Page 56: Object-Oriented programming 1 SSD3: Object-Oriented Programming and Design

Object-Oriented programmingObject-Oriented programming 5757

The Wrapper ClassesThe 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. They are called the wrapper classes ( 包装类 ) java.lang.Byte java.lang.Short

java.lang.Integer java.lang.Long java.lang.Character java.lang.Floatjava.lang.Double java.lang.Boolean

Page 57: Object-Oriented programming 1 SSD3: Object-Oriented Programming and Design

Object-Oriented programmingObject-Oriented programming 5858

The Wrapper ClassesThe Wrapper ClassesNotice :

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.

Page 58: Object-Oriented programming 1 SSD3: Object-Oriented Programming and Design

Object-Oriented programmingObject-Oriented programming 5959

PrimitivesPrimitives String objects String objects The wrapper classes provide methods for

converting primitives to String objects 基本类型转字

符串对象E.g., Integer.toString(10) converts the integer value 10 to the

String "10",String objects to primitives 字符串对象转

基本类型E.g., Integer.parseInt("10") converts the String "10" to the integer

value 10.

Page 59: Object-Oriented programming 1 SSD3: Object-Oriented Programming and Design

Object-Oriented programmingObject-Oriented programming 6060

PrimitivesPrimitives String objects String objects Sample code(ProductValue.java) enhance the

application ProductInfo(ProductInfo.java).

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.

Page 60: Object-Oriented programming 1 SSD3: Object-Oriented Programming and Design

Object-Oriented programmingObject-Oriented programming 6161

1.1.4 Console I/O1.1.4 Console I/O

The java.io Package Reading Primitive Values

Page 61: Object-Oriented programming 1 SSD3: Object-Oriented Programming and Design

Object-Oriented programmingObject-Oriented programming 6262

The java.io Package 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.

Page 62: Object-Oriented programming 1 SSD3: Object-Oriented Programming and Design

Object-Oriented programmingObject-Oriented programming 6363

System.in, System.out, System.errSystem.in, System.out, System.errSystem.in

the "standard" input stream. corresponds to keyboard input.

System.outthe "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.

Page 63: Object-Oriented programming 1 SSD3: Object-Oriented Programming and Design

Object-Oriented programmingObject-Oriented programming 6464

Println() and print() methodPrintln() and print() methodSystem.out and System.err could be used for

output directly. But if wrap each in a PrintWriter object is

more convenient (see sample code, compared with output directly). The class PrintWriter has two printing methods:

println and print. Println() automatically follows the output with a new

line; Print() does not output with a new line; The println() and print() can take many types of

arguments. 可输出各种基本类型的数据Sample code(PrintlnDemo.java)

Page 64: Object-Oriented programming 1 SSD3: Object-Oriented Programming and Design

Object-Oriented programmingObject-Oriented programming 6565

automatic automatic flushingflushing 直接发送直接发送 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

Page 65: Object-Oriented programming 1 SSD3: Object-Oriented Programming and Design

Object-Oriented programmingObject-Oriented programming 6666

automatic automatic flushingflushing 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 println() but not after calls to method print(). The programmer can use the flush() to flush the buffer

after a call to print(). Sample code(Hello.java ) illustrates the use of

method flush.

Page 66: Object-Oriented programming 1 SSD3: Object-Oriented Programming and Design

Object-Oriented programmingObject-Oriented programming 6767

Some explain of sample codeSome 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 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.

Page 67: Object-Oriented programming 1 SSD3: Object-Oriented Programming and Design

Object-Oriented programmingObject-Oriented programming 6868

Reading Primitive Values Reading Primitive Values Not all input is intended to be used as a String.

程序从键盘接受的输入都是 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

Notice: Most wrapper classes have a similar parse method:

class Double : parseDouble() class Float : parseFloat(). class Boolean : getBoolean(), not parseBoolean()

Page 68: Object-Oriented programming 1 SSD3: Object-Oriented Programming and Design

Object-Oriented programmingObject-Oriented programming 6969

How to extract(How to extract( 提取提取 ) a character from the input) 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)

Page 69: Object-Oriented programming 1 SSD3: Object-Oriented Programming and Design

Object-Oriented programmingObject-Oriented programming 7070

extract a character from the inputextract a character from the input

uses a StringTokenizer object to read three integers from one line of input

Sample code (ReadThreeIntegers.java )

Page 70: Object-Oriented programming 1 SSD3: Object-Oriented Programming and Design

Object-Oriented programmingObject-Oriented programming 7171

1.1.5 Exception Objects1.1.5 Exception Objects

Exception Handling 异常处理Exception Objects Exception Classes User-Defined Exceptions The try-catch Block The throws Clause throws 子句 The throw Statement throw 语句Documenting Exceptions Using Javadoc

Page 71: Object-Oriented programming 1 SSD3: Object-Oriented Programming and Design

Object-Oriented programmingObject-Oriented programming 7272

Exception Handling 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.

Page 72: Object-Oriented programming 1 SSD3: Object-Oriented Programming and Design

Object-Oriented programmingObject-Oriented programming 7373

Pseudo-code for Exception AnalysisPseudo-code for Exception Analysis In traditional programming

include conditional statements( 条件语句 ) to detect and handle program failures.

this code is difficult to read and maintain. Pseudo-code( 伪代码 ) for a method that reads an integer

from the standard inputint 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".

Page 73: Object-Oriented programming 1 SSD3: Object-Oriented Programming and Design

Object-Oriented programmingObject-Oriented programming 7474

add code to detect / handle potential failuresadd code to detect / handle potential failuresint 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; }

} }

}

Page 74: Object-Oriented programming 1 SSD3: Object-Oriented Programming and Design

Object-Oriented programmingObject-Oriented programming 7575

Exception handling Exception handling mechanism 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.Java how to handle exception

the normal flow of the code is specified in the body of a try block ( try 语句块)

each failure is handled in a catch block ( catch 语句块) separated from the normal flow of the code.

Page 75: Object-Oriented programming 1 SSD3: Object-Oriented Programming and Design

Object-Oriented programmingObject-Oriented programming 7676

pseudo-code that uses exception handlingpseudo-code that uses exception handlingint 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; }

} }

Page 76: Object-Oriented programming 1 SSD3: Object-Oriented Programming and Design

Object-Oriented programmingObject-Oriented programming 7777

Exception ObjectsException 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

Page 77: Object-Oriented programming 1 SSD3: Object-Oriented Programming and Design

Object-Oriented programmingObject-Oriented programming 7878

sequence of throwing exceptionsequence 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.

Sample code (ExceptionDemo.java). 观察 throw 及 throws 的位置, 体会区别

Page 78: Object-Oriented programming 1 SSD3: Object-Oriented Programming and Design

Object-Oriented programmingObject-Oriented programming 7979

figure illustrates exception throwing and catching figure illustrates exception throwing and catching

Page 79: Object-Oriented programming 1 SSD3: Object-Oriented Programming and Design

Object-Oriented programmingObject-Oriented programming 8080

ExceptionDemo analysisExceptionDemo 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. 异常抛出前各方法的调用顺序

Page 80: Object-Oriented programming 1 SSD3: Object-Oriented Programming and Design

Object-Oriented programmingObject-Oriented programming 8181

NOTICENOTICE 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(),

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

Page 81: Object-Oriented programming 1 SSD3: Object-Oriented Programming and Design

Object-Oriented programmingObject-Oriented programming 8282

information stored in the Exception object.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 the print statements in methodB and methodC were

never executed. Why?

Page 82: Object-Oriented programming 1 SSD3: Object-Oriented Programming and Design

Object-Oriented programmingObject-Oriented programming 8383

Exception objects’ methods Exception objects’ methods String getMessage().

Return: the argument that was passed to the constructor of

the exception object. 就是传给异常对象构造方法的那个参数

String toString(). Return:

The name of the exception (its type) + “:” +getMessage().

void printStackTrace(). This method displays in the standard error stream Return:

toString() + information that shows where the exception was thrown

including a list of all the methods that were called before the exception occurred

Page 83: Object-Oriented programming 1 SSD3: Object-Oriented Programming and Design

Object-Oriented programmingObject-Oriented programming 8484

Exception Classes Exception Classes

Exception objects are instances of classes that descend from class Throwable.由 Throwable 派生出来的子类的实例

Throwable has 2 subclasses:Error

Class Error is used for serious problems from which an application is unlikely to recover. 无法恢复的!

E.g., "out of memory" error.

Exception. Class Exception is used for abnormal conditions that

an application can be expected to handled.

Page 84: Object-Oriented programming 1 SSD3: Object-Oriented Programming and Design

Object-Oriented programmingObject-Oriented programming 8585

Hierarchy of exceptionsHierarchy of exceptions

Page 85: Object-Oriented programming 1 SSD3: Object-Oriented Programming and Design

Object-Oriented programmingObject-Oriented programming 8686

checked checked and and unchecked exceptionsunchecked exceptions

two categories of Java exceptions Unchecked (未检查) exceptions : Exceptions

that are not "checked" by the compiler checked (已检查) exceptions : exceptions

that are "checked" by the compilerRemember:

unchecked exceptions The classes RuntimeException, Error and their subclasses 及其子类

All other exception classes are checked exceptions.

Page 86: Object-Oriented programming 1 SSD3: Object-Oriented Programming and Design

Object-Oriented programmingObject-Oriented programming 8787

代码中必须处理所有 代码中必须处理所有 checked exceptionschecked exceptions

The compiler will not compile a fileif it contains a method where a checked

exception may occur the method does

not handle the checked exception in a catch block catch 捕捉并自行处理

Or not list it in the method header. throws 抛出让其他程序处理,在方法头部处理声明参数、返回值、以及方法执行时

Page 87: Object-Oriented programming 1 SSD3: Object-Oriented Programming and Design

Object-Oriented programmingObject-Oriented programming 8888

Hierarchy of exceptionsHierarchy of exceptions

Page 88: Object-Oriented programming 1 SSD3: Object-Oriented Programming and Design

Object-Oriented programmingObject-Oriented programming 8989

User-Defined Exceptions 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.

Page 89: Object-Oriented programming 1 SSD3: Object-Oriented Programming and Design

Object-Oriented programmingObject-Oriented programming 9090

How to handle exceptions?How to handle exceptions?The try{ } catch{ } Block 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 }……

Page 90: Object-Oriented programming 1 SSD3: Object-Oriented Programming and Design

Object-Oriented programmingObject-Oriented programming 9191

The try{ } catch{ } Block The try{ } catch{ } Block ExceptionType is the class name of the

exception that the catch block will handle. Notice

catch block looks like method header because it has an argument.

Page 91: Object-Oriented programming 1 SSD3: Object-Oriented Programming and Design

Object-Oriented programmingObject-Oriented programming 9292

Many catch blocks can appear after a try Many catch blocks can appear after a try blockblock

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. 依次在各 catch 中比较 match found,

the body of the matching catch block is executed. Execution continue after the last catch block. 执行 try 语句块之后

的语句 no match found

the exception is passed up the call stack

Sample code( IntegerReader.java) readInteger() that reads an integer from the standard input

Page 92: Object-Oriented programming 1 SSD3: Object-Oriented Programming and Design

Object-Oriented programmingObject-Oriented programming 9393

Code analysis of IntegerReader.java Code analysis of IntegerReader.java line 43 :

BufferedReader.readLine() at might throw an IOException. 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.

Page 93: Object-Oriented programming 1 SSD3: Object-Oriented Programming and Design

Object-Oriented programmingObject-Oriented programming 9494

notenote The argument of a catch block can be misleading.

the following catch block will catch an IOException;

catch (IOException e) { // code to handle IOException, FileNotFoundException,

//and EOFException }

But for IOException, it will also catch FileNotFoundException and EOFException.

Why? because the classes FileNotFoundException and EOFException are subclasses of class IOException

捕捉的异常越具体越好 , 不要太笼统

Page 94: Object-Oriented programming 1 SSD3: Object-Oriented Programming and Design

Object-Oriented programmingObject-Oriented programming 9595

The throws Clause The throws Clause (( throwsthrows 子句)子句) 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.

Page 95: Object-Oriented programming 1 SSD3: Object-Oriented Programming and Design

Object-Oriented programmingObject-Oriented programming 9696

The throws Clause The throws Clause (( throwsthrows 子句)子句)Unchecked exceptions may not be listed in a

throws clause,why? Because the compiler does not require it.

未检查异常通常是严重出错,无法恢复程序正常执行

Page 96: Object-Oriented programming 1 SSD3: Object-Oriented Programming and Design

Object-Oriented programmingObject-Oriented programming 9797

Sample code analysisSample 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 IOExceptionthe exception object is passed to the Java Virtual

Machine (JVM). The JVM

displays the exception information and terminates the program.

xqw
w4
Page 97: Object-Oriented programming 1 SSD3: Object-Oriented Programming and Design

Object-Oriented programmingObject-Oriented programming 9898

The throw Statement The throw Statement (( throwsthrows 语句)语句)User-defined methods can also throw

exceptions. How to do? 主动抛出异常Use the keyword throw following by an exception

object. The exception object is created like any other

object, using the new operator and a constructor. throw new OutOfRangeException(); throw new OutOfRangeException("Not a valid

number");

Page 98: Object-Oriented programming 1 SSD3: Object-Oriented Programming and Design

Object-Oriented programmingObject-Oriented programming 9999

Sample codeSample code

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.

Page 99: Object-Oriented programming 1 SSD3: Object-Oriented Programming and Design

Object-Oriented programmingObject-Oriented programming 100100

1.1.6 Code Conventions 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.

Page 100: Object-Oriented programming 1 SSD3: Object-Oriented Programming and Design

Object-Oriented programmingObject-Oriented programming 101101

Good programming styleGood 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.

Page 101: Object-Oriented programming 1 SSD3: Object-Oriented Programming and Design

Object-Oriented programmingObject-Oriented programming 102102

A good style of programmingA good style of programming 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. 可读性

the name 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.

Page 102: Object-Oriented programming 1 SSD3: Object-Oriented Programming and Design

Object-Oriented programmingObject-Oriented programming 103103

When use conventionsWhen 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. 强烈推荐使用 Sun公司的编码规约

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.

Page 103: Object-Oriented programming 1 SSD3: Object-Oriented Programming and Design

Object-Oriented programmingObject-Oriented programming 104104

1.1.7 Javadoc 1.1.7 Javadoc

Javadoc and the Javadoc Program Advice on Documenting Javadoc SyntaxReference Standard Java API Document

Page 104: Object-Oriented programming 1 SSD3: Object-Oriented Programming and Design

Object-Oriented programmingObject-Oriented programming 105105

Javadoc and Javadoc ProgramJavadoc and Javadoc ProgramJavadoc comments are

written by the programmer 由程序员写注释processed by the program Javadoc. 由工具处理

A tool Software ( included in JDK)Parses the Javadoc comments and the overall

structure of the program, producing a set of HTML pages that serve as

documentation for the program.

Page 105: Object-Oriented programming 1 SSD3: Object-Oriented Programming and Design

Object-Oriented programmingObject-Oriented programming 106106

Advice on Documenting Advice on Documenting Do you know?

To maintain software costs significantly more than to develop it. ( 60倍)

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.

Page 106: Object-Oriented programming 1 SSD3: Object-Oriented Programming and Design

Object-Oriented programmingObject-Oriented programming 107107

Javadoc Syntax 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 */

Page 107: Object-Oriented programming 1 SSD3: Object-Oriented Programming and Design

Object-Oriented programmingObject-Oriented programming 108108

Javadoc tags Javadoc tags 标签标签 Javadoc comments include Javadoc tags. Tag describes a

particular attribute of the entity being commented. Format : @TagName

1. @author – programmer's name; used for classes

2. @version – version of the program; used for classes

3. @param – description of a formal parameter; used for methods and constructors

4. @return – description of a return value; used for methods

5. @exception (or @throws) – description of an exception; used for methods and constructors

6. @see – reference to a related entity; used for classes, constructors, methods, and data fields

Page 108: Object-Oriented programming 1 SSD3: Object-Oriented Programming and Design

Object-Oriented programmingObject-Oriented programming 109109

Documenting Exceptions Using Javadoc Documenting Exceptions Using Javadoc

The Javadoc tag for an exception is the @throws tag — the @exception tag can also be used.

The Javadoc comment ( 符合 javadoc 规范的注释 ) 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. 处理了就没有必要加@throws tag

Page 109: Object-Oriented programming 1 SSD3: Object-Oriented Programming and Design

Object-Oriented programmingObject-Oriented programming 110110

Documenting Exceptions Using Javadoc Documenting Exceptions Using Javadoc

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. 描写怎么样的情形会导致异常

Page 110: Object-Oriented programming 1 SSD3: Object-Oriented Programming and Design

Object-Oriented programmingObject-Oriented programming 111111

Javadoc tagsJavadoc tags 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)

Page 111: Object-Oriented programming 1 SSD3: Object-Oriented Programming and Design

Object-Oriented programmingObject-Oriented programming 112112

the the javadocjavadoc command command javadoc produce a collection of HTML pages

document classes

Or , use Javadoc in IDE tools , Eclipse SDK

Page 112: Object-Oriented programming 1 SSD3: Object-Oriented Programming and Design

Object-Oriented programmingObject-Oriented programming 113113

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

Page 113: Object-Oriented programming 1 SSD3: Object-Oriented Programming and Design

Object-Oriented programmingObject-Oriented programming 114114

The Process of Debugging 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. 起码要对充分理解程序代码

Page 114: Object-Oriented programming 1 SSD3: Object-Oriented Programming and Design

Object-Oriented programmingObject-Oriented programming 115115

effective technique for debugging a program effective technique for debugging a program

Page 115: Object-Oriented programming 1 SSD3: Object-Oriented Programming and Design

Object-Oriented programmingObject-Oriented programming 116116

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

Page 116: Object-Oriented programming 1 SSD3: Object-Oriented Programming and Design

Object-Oriented programmingObject-Oriented programming 117117

Debugging resultDebugging 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.

Page 117: Object-Oriented programming 1 SSD3: Object-Oriented Programming and Design

Object-Oriented programmingObject-Oriented programming 118118

The Debugger 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 NetBean, Borland JBuilder, and BlueJ, contain their own debuggers.

Stand-alone graphical debuggers, such as JSwat and DDD

Text-based debuggers, such as Sun jdb

Page 118: Object-Oriented programming 1 SSD3: Object-Oriented Programming and Design

Object-Oriented programmingObject-Oriented programming 119119

Debuggers’ capabilities: 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.

Page 119: Object-Oriented programming 1 SSD3: Object-Oriented Programming and Design

Object-Oriented programmingObject-Oriented programming 120120

Note of debuggerNote 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. 主要依靠编程者的调试经验

Page 120: Object-Oriented programming 1 SSD3: Object-Oriented Programming and Design

Object-Oriented programmingObject-Oriented programming 121121

1.1.9 Debugging with Eclipse 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

Page 121: Object-Oriented programming 1 SSD3: Object-Oriented Programming and Design

Object-Oriented programmingObject-Oriented programming 122122

IntroductionIntroductionThis section 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

Page 122: Object-Oriented programming 1 SSD3: Object-Oriented Programming and Design

Object-Oriented programmingObject-Oriented programming 123123

The Example The Example Sample code (Employee.java )

Page 123: Object-Oriented programming 1 SSD3: Object-Oriented Programming and Design

Object-Oriented programmingObject-Oriented programming 124124

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