144
Object-Oriented Programming Language Revised: Nov-2006@TW V0.5 OO 語語語語 -Java 語語

Object-Oriented Programming Language Revised: Nov-2006@TW V0.5 OO 語言簡要 -Java 案例

Embed Size (px)

Citation preview

Page 1: Object-Oriented Programming Language Revised: Nov-2006@TW V0.5 OO 語言簡要 -Java 案例

Object-Oriented Programming Language

Revised: Nov-2006@TW

V0.5

OO 語言簡要 -Java 案例

Page 2: Object-Oriented Programming Language Revised: Nov-2006@TW V0.5 OO 語言簡要 -Java 案例

Programming Languages

• Computer programmers write programs for computers using one or more programming languages

• Some languages are better for one type of program or one style of user interface than for others

• You may have heard of some programming languages: COBOL, Basic, Pascal, C/C++, Java, Assembly Language, and Others

Page 3: Object-Oriented Programming Language Revised: Nov-2006@TW V0.5 OO 語言簡要 -Java 案例

Programming Languages

• A programming language specifies the words and symbols that we can use to write a program

• A programming language employs a set of rules that dictate how the words and symbols can be put together to form valid program statements

• A programming language has both syntax and semantics

Page 4: Object-Oriented Programming Language Revised: Nov-2006@TW V0.5 OO 語言簡要 -Java 案例

4

Syntax and Semantics

• The syntax rules of a language define how we can put together symbols, reserved words, and identifiers to make a valid program

• The semantics of a program statement define what that statement means (its purpose or role in a program)

• A program that is syntactically correct is not necessarily logically (semantically) correct

• A program will always do what we tell it to do, not what we meant to tell it to do

Page 5: Object-Oriented Programming Language Revised: Nov-2006@TW V0.5 OO 語言簡要 -Java 案例

5

Language Levels

• There are four programming language levels:– machine language– assembly language– high-level language– fourth-generation language

• Each type of CPU has its own specific machine language

• The other levels were created to make it easier for a human being to read and write programs

Page 6: Object-Oriented Programming Language Revised: Nov-2006@TW V0.5 OO 語言簡要 -Java 案例

6

Programming Languages• Each type of CPU executes only a particular

machine language

• A program must be translated into machine language before it can be executed

• A compiler is a software tool which translates source code into a specific target language

• Often, that target language is the machine language for a particular type of CPU

• The Java approach is somewhat different

Page 7: Object-Oriented Programming Language Revised: Nov-2006@TW V0.5 OO 語言簡要 -Java 案例

7

Java Translation

• The Java compiler translates Java source code into a special representation called bytecode in the .class file

• Java bytecode is not the machine language for any specific CPU

• Another software tool, called an interpreter (in our case the Java Virtual Machine), executes the bytecode

• Java is considered to be architecture-neutral

• The Java compiler is not tied to any particular machine

• The JVM can be implemented on any machine

Page 8: Object-Oriented Programming Language Revised: Nov-2006@TW V0.5 OO 語言簡要 -Java 案例

Java Program Structure

• In the Java programming language:– A program is made up of one or more classes– A class contains zero or more attributes– A class contains one or more methods– A method contains program statements

• These terms will be explored in detail throughout the course

• A Java application starts with a class containing a method called main

• See Lincoln.java (page 28)

Page 9: Object-Oriented Programming Language Revised: Nov-2006@TW V0.5 OO 語言簡要 -Java 案例

9

Java Program Structure

public class MyProgram

{

}

// comments about the class

class header

class body

Comments can be placed almost anywhere

Page 10: Object-Oriented Programming Language Revised: Nov-2006@TW V0.5 OO 語言簡要 -Java 案例

10

Java Program Structure

public class MyProgram

{

}

// comments about the class

public static void main (String[] args)

{

}

// comments about the method

method headermethod body

// comments about the attributes

attribute definitions

Page 11: Object-Oriented Programming Language Revised: Nov-2006@TW V0.5 OO 語言簡要 -Java 案例

11

Comments• Comments in a program are called inline

documentation

• They should be included to explain the purpose of the program and describe processing steps

• They do not affect how a program works

• Java comments can take three forms:

// this comment runs to the end of the line

/* this comment runs to the terminating symbol, even across line breaks */

/** this is a javadoc comment */

Page 12: Object-Oriented Programming Language Revised: Nov-2006@TW V0.5 OO 語言簡要 -Java 案例

12

Identifiers• Identifiers are the words a programmer uses in a program

• An identifier can be made up of letters, digits, the underscore character ( _ ), and the dollar sign

• Identifiers cannot begin with a digit

• Java is case sensitive - Total, total, and TOTAL are different identifiers

• By convention, programmers use different case styles for different types of identifiers, such as– title case for class names - Lincoln

– lower case for object or other variable names – current

– upper case for constants – MAXIMUM

Page 13: Object-Oriented Programming Language Revised: Nov-2006@TW V0.5 OO 語言簡要 -Java 案例

Identifiers

• Sometimes we choose identifiers ourselves when writing a program (such as Lincoln)

• Sometimes we are using another programmer's code, so we use the identifiers that he or she chose (such as println)

• Often we use special identifiers called reserved words that already have a predefined meaning in the language

• A reserved word cannot be used in any other way

Page 14: Object-Oriented Programming Language Revised: Nov-2006@TW V0.5 OO 語言簡要 -Java 案例

14

Reserved Words

• The Java reserved words:abstractbooleanbreakbytecasecatchcharclassconstcontinuedefaultdodouble

elseenumextendsfalsefinalfinallyfloatforgotoifimplementsimportinstanceof

intinterfacelongnativenewnullpackageprivateprotectedpublicreturnshortstatic

strictfpsuperswitchsynchronizedthisthrowthrowstransienttruetryvoidvolatilewhile

Page 15: Object-Oriented Programming Language Revised: Nov-2006@TW V0.5 OO 語言簡要 -Java 案例

15

White Space• Spaces, blank lines, and tabs are called white

space

• White space is used to separate words and symbols in a program

• Extra white space is ignored

• A valid Java program can be formatted many ways

• Programs should be formatted to enhance readability, using consistent indentation

Page 16: Object-Oriented Programming Language Revised: Nov-2006@TW V0.5 OO 語言簡要 -Java 案例

Problem Solving• The purpose of writing a program is to solve a problem

• Solving a problem consists of multiple activities:

– Understand the problem– Design a solution– Consider alternatives and refine the solution– Implement the solution– Test the solution

• These activities are not purely linear – they overlap and interact

• Top-Down vs. Bottom-Up Approach

Page 17: Object-Oriented Programming Language Revised: Nov-2006@TW V0.5 OO 語言簡要 -Java 案例

Problem Solving

• The key to designing a solution is breaking it down into manageable pieces

• When writing software, we design separate pieces that are responsible for certain parts of the solution

• An object-oriented approach lends itself to this kind of solution decomposition

• We will dissect our solutions into pieces called objects and classes

Page 18: Object-Oriented Programming Language Revised: Nov-2006@TW V0.5 OO 語言簡要 -Java 案例

Object-Oriented Programming

• Java is an object-oriented programming language

• As the term implies, an object is a fundamental entity in a Java program

• Objects can be used effectively to represent real-world entities

• For instance, an object might represent a bank account

• Each bank account object handles the processing and data management related to that bank account

Page 19: Object-Oriented Programming Language Revised: Nov-2006@TW V0.5 OO 語言簡要 -Java 案例

19

Objects

• An object has:

– state - descriptive characteristics

– behaviors - what it can do (or what can be done to it)

• The state of a bank account includes its balance

• The behaviors associated with a bank account include the ability to get the balance, make deposits, and make withdrawals

• Note that the behavior of an object might change its state, e.g. making a deposit will increase the balance

Page 20: Object-Oriented Programming Language Revised: Nov-2006@TW V0.5 OO 語言簡要 -Java 案例

Classes

• An object is defined by a class representing a concept

• A class is the blueprint for each instance of an object

• Multiple objects can be created from the same class

• A class has attributes that define the state of each object

• A class has methods that define the behavior of the object

• The class that contains the main method represents the starting point for a Java program

• The program can and usually does contain more classes than just the one that contains the main method

Page 21: Object-Oriented Programming Language Revised: Nov-2006@TW V0.5 OO 語言簡要 -Java 案例

Objects and Classes

A Class(The Concept)

John’s Bank AccountBalance: $5,257.51

Three objects(Three Instancesof the Concept)

Bill’s Bank AccountBalance: $1,245,069.89

Mary’s Bank AccountBalance: $16,833.27

Multiple objectsof the same class

BankAccount

- balance: float

+ getBalance(): float+ deposit(float amount): bool+ withdraw(float amount): bool

Page 22: Object-Oriented Programming Language Revised: Nov-2006@TW V0.5 OO 語言簡要 -Java 案例

Part-2 Components

•Overview•GUI Applictions

•General Concepts•Control statements

Page 23: Object-Oriented Programming Language Revised: Nov-2006@TW V0.5 OO 語言簡要 -Java 案例

23

Java Program Structure-1public class BankAccount

{

}

public float getBalance(){

}public boolean deposit(float amount){

}public boolean withdraw(float amount){

}

method body

attribute definitionprivate float balance;

method body

method body

Page 24: Object-Oriented Programming Language Revised: Nov-2006@TW V0.5 OO 語言簡要 -Java 案例

Java Program Structure -2

int book0, book1, book2, book3, book4;for (int i = 0; i < 5; i++) {

switch (i) {case 0:

statements using book0;break;

case 1:same statements using book1;break;

// three more cases needed here }

}

Page 25: Object-Oriented Programming Language Revised: Nov-2006@TW V0.5 OO 語言簡要 -Java 案例

陣列物件 : Arrays of Objects

• To create some String objects and store them in elements of the array:

“friendship”

words

-

-

“loyalty”

“honor”

words[0] = new String(“friendship”);words[1] = “loyalty”;words[2] = “honor”;

Page 26: Object-Oriented Programming Language Revised: Nov-2006@TW V0.5 OO 語言簡要 -Java 案例

Arrays of Objects

• String objects can be created using literals

• The following declaration creates an array object called verbs with a length of 4 and fills it with references to four String objects created using string literals

String[] verbs = {"play", "work", "eat", "sleep"};

Page 27: Object-Oriented Programming Language Revised: Nov-2006@TW V0.5 OO 語言簡要 -Java 案例

Methods:Array Object• To use one of the methods of an object element

of an array:verbs[2].equals(“eat”); // true

• To pass one of the object elements of an array as a parameter to a method:“eat”.equals(verbs[2]); // true

• To return an element of an array:public String methodName(verbs){return verbs[2]; // “eat”

}

Page 28: Object-Oriented Programming Language Revised: Nov-2006@TW V0.5 OO 語言簡要 -Java 案例

Graphical Applications

• The example programs we've explored thus far have been text-based command-line applications, which interact with the user using text prompts

• Let's examine some Java applications that have graphical components

• These components will serve as a foundation to programs with true graphical user interfaces (GUIs)

• We will start with generating a frame with panels containing text “labels” or images

Page 29: Object-Oriented Programming Language Revised: Nov-2006@TW V0.5 OO 語言簡要 -Java 案例

Graphical Applications

• GUI-related classes are defined primarily in java.awt and javax.swing packages

• The Abstract Windowing Toolkit (AWT) was the original Java GUI package

• The Swing package provides additional and more versatile components

• Sometimes called Java Foundation Classes (mimicking Microsoft Foundation Classes)

Page 30: Object-Oriented Programming Language Revised: Nov-2006@TW V0.5 OO 語言簡要 -Java 案例

Graphical Applications

• GUI-related classes are defined primarily in java.awt and javax.swing packages

• The Abstract Windowing Toolkit (AWT) was the original Java GUI package

• The Swing package provides additional and more versatile components

• Sometimes called Java Foundation Classes (mimicking Microsoft Foundation Classes)

Page 31: Object-Oriented Programming Language Revised: Nov-2006@TW V0.5 OO 語言簡要 -Java 案例

GUI Containers - Frame

• A GUI container is a component that is used to hold and organize other components

• JFrame, JDialog, and JApplet are the three top level containers that are used to display graphics in GUI applications

• A JFrame is displayed as a separate window with a title bar – it can be repositioned and resized on the screen as needed

Page 32: Object-Oriented Programming Language Revised: Nov-2006@TW V0.5 OO 語言簡要 -Java 案例

Frame-based Hello WorldJFrame frame attribute titleJFrame frame

JLabel label

JFrame frame width = 300

JFrame frameheight = 200

Page 33: Object-Oriented Programming Language Revised: Nov-2006@TW V0.5 OO 語言簡要 -Java 案例

Frame-based Hello Worldimport javax.swing.*; // Get JFrame and JLabel classes

public class HelloWorld { public static void main(String[] args) { //Create and set up the window. JFrame frame = new JFrame("HelloWorld Using Swing"); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

//Add the ubiquitous "Hello World" label. JLabel label = new JLabel("Hello World"); frame.add(label);

//Display the window. frame.setSize(300,200); // width and height frame.setVisible(true); }}

Page 34: Object-Oriented Programming Language Revised: Nov-2006@TW V0.5 OO 語言簡要 -Java 案例

GUI Panels / Components

• A panel is a container that cannot be displayed on its own

• It must be added to another container to be displayed

• It is used to organize other components• A GUI component is an object that

represents a screen element such as a text field or an image

• A GUI component must be added to a container such as a panel or frame to be displayed

Page 35: Object-Oriented Programming Language Revised: Nov-2006@TW V0.5 OO 語言簡要 -Java 案例

GUI Containers

• A GUI container can be classified as either heavyweight or lightweight

• A heavyweight container is one that is managed by the underlying operating system

• A lightweight container is managed by the Java program itself

• Occasionally this distinction is important• A frame is a heavyweight container and a

panel is a lightweight container

Page 36: Object-Oriented Programming Language Revised: Nov-2006@TW V0.5 OO 語言簡要 -Java 案例

Labels• A label is a GUI component that displays a

line of text• Labels are usually used to display

information or identify other components in the display

• Let's look at a program that organizes two labels in a panel and displays that panel in a frame

• See Authority.java This program is not interactive, but the frame can be repositioned and resized

Page 37: Object-Oriented Programming Language Revised: Nov-2006@TW V0.5 OO 語言簡要 -Java 案例

Authority

JLabel label1

JLabel label2

JPanel primary

JFrame frame

Page 38: Object-Oriented Programming Language Revised: Nov-2006@TW V0.5 OO 語言簡要 -Java 案例

Authority.javaimport java.awt.*;import javax.swing.*;

public class Authority{public static void main (String[] args) { JFrame frame = new JFrame ("Authority"); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

JPanel primary = new JPanel(); primary.setBackground (Color.yellow); primary.setPreferredSize (new Dimension(250, 75));

Page 39: Object-Oriented Programming Language Revised: Nov-2006@TW V0.5 OO 語言簡要 -Java 案例

Authority.java

JLabel label1 = new JLabel ("Question authority,"); JLabel label2 = new JLabel ("but raise your hand first.");

primary.add (label1); primary.add (label2);

frame.add(primary); frame.pack(); frame.setVisible(true);

}}

Page 40: Object-Oriented Programming Language Revised: Nov-2006@TW V0.5 OO 語言簡要 -Java 案例

Getting started…

Simple statements

Basic Concepts

Page 41: Object-Oriented Programming Language Revised: Nov-2006@TW V0.5 OO 語言簡要 -Java 案例

Expressions, Data Conversion, and Input

• Expressions

• Operators and Precedence

• Assignment Operators

• Data Conversion

• Input and the Scanner Class

Page 42: Object-Oriented Programming Language Revised: Nov-2006@TW V0.5 OO 語言簡要 -Java 案例

Expressions

• An expression is a combination of one or more operators and operands

• Arithmetic expressions compute numeric results and make use of the arithmetic operators:

• If either or both operands used by an arithmetic operator are floating point, then the result is a floating point

Addition +Subtraction -Multiplication *Division /Remainder %

Page 43: Object-Oriented Programming Language Revised: Nov-2006@TW V0.5 OO 語言簡要 -Java 案例

Division and Remainder

• If both operands to the division operator (/) are integers, the result is an integer (the fractional part is discarded)

• The remainder operator (%) returns the remainder after dividing the second operand into the first

14 / 3 equals

8 / 12 equals

4

0

14 % 3 equals

8 % 12 equals

2

8

Page 44: Object-Oriented Programming Language Revised: Nov-2006@TW V0.5 OO 語言簡要 -Java 案例

Operator Precedence• Operators can be combined into complex expressions

result = total + count / max - offset;

• Operators have a well-defined precedence which determines the order in which they are evaluated

• Multiplication, division, and remainder are evaluated prior to addition, subtraction, and string concatenation

• Arithmetic operators with the same precedence are evaluated from left to right, but parentheses can be used to force the evaluation order

• See Appendix D for a more complete list of operators and their precedence.

Page 45: Object-Oriented Programming Language Revised: Nov-2006@TW V0.5 OO 語言簡要 -Java 案例

Operator Precedence

• What is the order of evaluation in the following expressions?

a + b + c + d + e1 432

a + b * c - d / e3 241

a / (b + c) - d % e2 341

a / (b * (c + (d - e)))4 123

Page 46: Object-Oriented Programming Language Revised: Nov-2006@TW V0.5 OO 語言簡要 -Java 案例

Expression Trees

• The evaluation of a particular expression can be shown using an expression tree

• The operators lower in the tree have higher precedence for that expression

a + (b – c) / da

+

/

- d

b c

Page 47: Object-Oriented Programming Language Revised: Nov-2006@TW V0.5 OO 語言簡要 -Java 案例

Assignment Revisited

• The assignment operator has a lower precedence than the arithmetic operators

First the expression on the right handside of the = operator is evaluated

Then the result is stored in thevariable on the left hand side

answer = sum / 4 + MAX * lowest;

14 3 2

Page 48: Object-Oriented Programming Language Revised: Nov-2006@TW V0.5 OO 語言簡要 -Java 案例

Assignment Revisited

• The right and left hand sides of an assignment statement can contain the same variable

First, one is added to theoriginal value of count

Then the result is stored back into count(overwriting the original value)

count = count + 1;

Page 49: Object-Oriented Programming Language Revised: Nov-2006@TW V0.5 OO 語言簡要 -Java 案例

Increment and Decrement

• The increment and decrement operators use only one operand

• The increment operator (++) adds one to its operand

• The decrement operator (--) subtracts one from its operand

• The statement

count++;

is functionally equivalent to

count = count + 1;

Page 50: Object-Oriented Programming Language Revised: Nov-2006@TW V0.5 OO 語言簡要 -Java 案例

Increment and Decrement

• The increment and decrement operators can be applied in postfix form:

count++

• or prefix form:

++count

• When used as part of a larger expression, the two forms can have different effects

• Because of their subtleties, the increment and decrement operators should be used with care

Page 51: Object-Oriented Programming Language Revised: Nov-2006@TW V0.5 OO 語言簡要 -Java 案例

Assignment Operators

• Often we perform an operation on a variable, and then store the result back into that variable

• Java provides assignment operators to simplify that process

• For example, the statement

num += count;

is equivalent to

num = num + count;

Page 52: Object-Oriented Programming Language Revised: Nov-2006@TW V0.5 OO 語言簡要 -Java 案例

Assignment Operators

• There are many assignment operators in Java, including the following:

Operator

+=-=*=/=%=

Example

x += yx -= yx *= yx /= yx %= y

Equivalent To

x = x + yx = x - yx = x * yx = x / yx = x % y

Page 53: Object-Oriented Programming Language Revised: Nov-2006@TW V0.5 OO 語言簡要 -Java 案例

Assignment Operators

• The right hand side of an assignment operator can be a complex expression

• The entire right-hand expression is evaluated first, then the result is combined with the original variable

• Therefore

result /= (total-MIN) % num;

is equivalent to

result = result / ((total-MIN) % num);

Page 54: Object-Oriented Programming Language Revised: Nov-2006@TW V0.5 OO 語言簡要 -Java 案例

Assignment Operators

• The behavior of some assignment operators depends on the types of the operands

• If the operands to the += operator are strings, the assignment operator performs string concatenation

• The behavior of an assignment operator (+=) is always consistent with the behavior of the corresponding operator (+)

Page 55: Object-Oriented Programming Language Revised: Nov-2006@TW V0.5 OO 語言簡要 -Java 案例

Data Conversion

• Sometimes it is convenient to convert data from one type to another

• For example, in a particular situation we may want to treat an integer as a floating point value

• These conversions do not change the type of a variable or the value that's stored in it – they only convert a value as part of a computation

Page 56: Object-Oriented Programming Language Revised: Nov-2006@TW V0.5 OO 語言簡要 -Java 案例

Data Conversion

• Conversions must be handled carefully to avoid losing information

• Widening conversions are safest because they tend to go from a small data type to a larger one (such as a short to an int)

• Narrowing conversions can lose information because they tend to go from a large data type to a smaller one (such as an int to a short)

• In Java, data conversions can occur in three ways:

– assignment conversion– promotion– casting

Page 57: Object-Oriented Programming Language Revised: Nov-2006@TW V0.5 OO 語言簡要 -Java 案例

Assignment Conversion

• Assignment conversion occurs when a value of one type is assigned to a variable of another

• If money is a float variable and dollars is an int variable, the following assignment converts the value in dollars to a float

money = dollars

• Only widening conversions can happen via assignment

• Note that the value or type of dollars did not change

Page 58: Object-Oriented Programming Language Revised: Nov-2006@TW V0.5 OO 語言簡要 -Java 案例

Data Conversion

• Promotion happens automatically when operators in expressions convert their operands

• For example, if sum is a float and count is an int, the value of count is converted to a floating point value to perform the following calculation:

result = sum / count;

Page 59: Object-Oriented Programming Language Revised: Nov-2006@TW V0.5 OO 語言簡要 -Java 案例

Casting

• Casting is the most powerful, and dangerous, technique for conversion

• Both widening and narrowing conversions can be accomplished by explicitly casting a value

• To cast, the type is put in parentheses in front of the value being converted

• For example, if total and count are integers, but we want a floating point result when dividing them, we can cast total:

result = (float) total / count;

Page 60: Object-Oriented Programming Language Revised: Nov-2006@TW V0.5 OO 語言簡要 -Java 案例

Reading Input

• Programs generally need input on which to operate

• The Scanner class provides convenient methods for reading input values of various types

• A Scanner object can be set up to read input from various sources, including from the user typing the values on the keyboard

• Keyboard input is represented by the System.in object

Page 61: Object-Oriented Programming Language Revised: Nov-2006@TW V0.5 OO 語言簡要 -Java 案例

Reading Input• The following line allows you to use the standard

library Scanner class in statements in your class:

import java.util.Scanner;

• The following line creates a Scanner object that reads from the keyboard:

Scanner scan = new Scanner(System.in);

• The new operator creates the Scanner object

• Once created, the Scanner object can be used to invoke various input methods, such as:

answer = scan.nextLine();

Page 62: Object-Oriented Programming Language Revised: Nov-2006@TW V0.5 OO 語言簡要 -Java 案例

Reading Input

• The Scanner class is part of the java.util class library and must be imported into a program to be used

• See Echo.java • The nextLine method reads all of the

input until the end of the line is found

Page 63: Object-Oriented Programming Language Revised: Nov-2006@TW V0.5 OO 語言簡要 -Java 案例

63

Java Program Structurepublic class BankAccount

{

}

public float getBalance(){

}public boolean deposit(float amount){

}public boolean withdraw(float amount){

}

method body

attribute definitionprivate float balance;

method body

method body

Page 64: Object-Oriented Programming Language Revised: Nov-2006@TW V0.5 OO 語言簡要 -Java 案例

Interactive Applications and Math

• Interactive Applications

• Command Line Interfaces

• The Math Class

• Example: Solving Quadratic Equations

• Example: Factoring the Solution

Page 65: Object-Oriented Programming Language Revised: Nov-2006@TW V0.5 OO 語言簡要 -Java 案例

Interactive Applications

• An interactive program with a command line interface contains a sequence of steps to:– Prompt the user to enter input data– Read and save the user’s responses– Process the data after all input(s) are received

• We can prompt the user: System.out.println(“prompt text”);

• We can read and format user responses:type variable = scan.nextType();

Page 66: Object-Oriented Programming Language Revised: Nov-2006@TW V0.5 OO 語言簡要 -Java 案例

Interactive Applications

• Similar to Quadratic.javaint a, b, c; // integer coefficientsScanner scan = new Scanner(System.in);

System.out.println(“Enter coefficient A”);a = scan.nextInt();System.out.println(“Enter coefficient B”);b = scan.nextInt();System.out.println(“Enter coefficient C”);c = scan.nextInt();// we have the data to solve the equation// ax-squared + bx + c = 0 for it’s roots

Page 67: Object-Oriented Programming Language Revised: Nov-2006@TW V0.5 OO 語言簡要 -Java 案例

We have the input values, now what?

• To solve the quadratic equation, we need to program in Java the formulas learned in high school algebra:discriminant = b squared – 4acroot1 = (-b + squareroot of discriminant)/2aroot2 = (-b - squareroot of discriminant)/2a

• How do we program those equations?• We need to use the Math Class Library,

Expression Evaluation, and Assignment

Page 68: Object-Oriented Programming Language Revised: Nov-2006@TW V0.5 OO 語言簡要 -Java 案例

Programming Basics

•Structured Programming

•Top-down Design

•Botton-Up Programming

Page 69: Object-Oriented Programming Language Revised: Nov-2006@TW V0.5 OO 語言簡要 -Java 案例

Boolean Expressions and If

• Flow of Control / Conditional Statements

• The if Statement

• Logical Operators

• The else Clause

• Block statements

• Nested if statements

Page 70: Object-Oriented Programming Language Revised: Nov-2006@TW V0.5 OO 語言簡要 -Java 案例

Flow of Control• Unless specified otherwise, the order of statement

execution through a method is linear:

– one statement after another in sequence

• Some programming statements allow us to:

– decide whether or not to execute a particular statement– execute a statement over and over, repetitively

• These decisions are based on boolean expressions (or conditions) that evaluate to true or false

• The order of statement execution is called the flow of control

Page 71: Object-Oriented Programming Language Revised: Nov-2006@TW V0.5 OO 語言簡要 -Java 案例

Conditional Statements

• A conditional statement lets us choose which statement will be executed next

• Therefore they are sometimes called selection statements

• Conditional statements give us the power to make basic decisions

• The Java conditional statements are the:

– if statement– if-else statement– switch statement

Page 72: Object-Oriented Programming Language Revised: Nov-2006@TW V0.5 OO 語言簡要 -Java 案例

72

The if Statement• The if statement has the following syntax:

if ( condition ) statement;

if is a Javareserved word

The condition must be aboolean expression. It mustevaluate to either true or false.

If the condition is true, the statement is executed.If it is false, the statement is skipped.

Page 73: Object-Oriented Programming Language Revised: Nov-2006@TW V0.5 OO 語言簡要 -Java 案例

73

Conditions/Boolean Expressions

• A condition is often obtained using an equality operator and/or relational operator which create boolean expressions that return boolean results:

== equal to!= not equal to< less than> greater than<= less than or equal to>= greater than or equal to

• Note the difference between the equality operator (==) and the assignment operator (=)

Page 74: Object-Oriented Programming Language Revised: Nov-2006@TW V0.5 OO 語言簡要 -Java 案例

The if Statement

• An example of an if statement:

• First the condition is evaluated -- the value of sum is either greater than the value of MAX, or it is not

• If the condition is true, the assignment statement is executed -- if it isn’t, it is skipped.

• Either way, the call to println is executed next

if (sum > MAX) delta = sum - MAX;System.out.println ("The sum is " + sum);

Page 75: Object-Oriented Programming Language Revised: Nov-2006@TW V0.5 OO 語言簡要 -Java 案例

75

The if-else Statement

• An else clause can be added to an if statement to make an if-else statement

• If the condition is true, statement1 is executed; if the condition is false, statement2 is executed

• One or the other will be executed, but not both

if ( condition ) statement1;else statement2;

Page 76: Object-Oriented Programming Language Revised: Nov-2006@TW V0.5 OO 語言簡要 -Java 案例

76

Block Statements

• Several statements can be grouped into a block statement delimited by braces

• A block statement can be used wherever a statement is called for in the Java syntax

if (total > MAX){ System.out.println ("Error!!"); errorCount++;}

Now the increment will only occur when the if condition is true

Page 77: Object-Oriented Programming Language Revised: Nov-2006@TW V0.5 OO 語言簡要 -Java 案例

77

Block Statements

• In an if-else statement, the if portion, or the else portion, or both, could be block statements

if (total > MAX){ System.out.println ("Error!!"); errorCount++;}else{ System.out.println ("Total: " + total); current = total*2;}

Page 78: Object-Oriented Programming Language Revised: Nov-2006@TW V0.5 OO 語言簡要 -Java 案例

78

The Conditional Operator

• Java has a conditional operator that uses a boolean condition to determine which of two expressions is evaluated

• Its syntax is:

condition ? expression1 : expression2

• If the condition is true, expression1 is evaluated; if it is false, expression2 is evaluated

• The value of the entire conditional operator is the value of the selected expression

Page 79: Object-Oriented Programming Language Revised: Nov-2006@TW V0.5 OO 語言簡要 -Java 案例

79

The Conditional Operator

• The conditional operator is similar to an if-else statement, except that it is an expression that returns a single value

• For example:

larger = ((num1 > num2) ? num1 : num2);

• If num1 is greater than num2, then num1 is assigned to larger; otherwise, num2 is assigned to larger

• The conditional operator is ternary because it requires three operands: a condition and two alternative values

Page 80: Object-Oriented Programming Language Revised: Nov-2006@TW V0.5 OO 語言簡要 -Java 案例

語言元件 : Repetition Statements• Repetition statements allow us to execute a

statement or a block of statements multiple times

• Often they are referred to as loops

• Like conditional statements, they are controlled by boolean expressions

• Java has three kinds of repetition statements:– the while loop– the do loop– the for loop

• The programmer should choose the right kind of loop for the situation

Page 81: Object-Oriented Programming Language Revised: Nov-2006@TW V0.5 OO 語言簡要 -Java 案例

81

The while Statement

• A while statement has the following syntax:

• If the condition is true, the statement is executed

• Then the condition is evaluated again, and if it is still true, the statement is executed again

• The statement is executed repeatedly until the condition becomes false

while ( condition ) statement;

Page 82: Object-Oriented Programming Language Revised: Nov-2006@TW V0.5 OO 語言簡要 -Java 案例

The while Statement

• An example of a while statement:

• If the condition of a while loop is false initially, the statement is never executed

• Therefore, the body of a while loop will execute zero or more times

int count = 1;while (count <= 5){ System.out.println (count); count++;}

Page 83: Object-Oriented Programming Language Revised: Nov-2006@TW V0.5 OO 語言簡要 -Java 案例

The do Statement

• An example of a do loop:

• The body of a do loop executes one or more times (Note: at least once)

int count = 0;do{ count++; System.out.println (count);} while (count < 5);

Page 84: Object-Oriented Programming Language Revised: Nov-2006@TW V0.5 OO 語言簡要 -Java 案例

The for Statement

• A for statement has the following syntax:

for ( initialization ; condition ; increment ) statement;

The initializationis executed once

before the loop begins

The statement isexecuted until the

condition becomes false

The increment portion is executed at the end of each

iteration

Page 85: Object-Oriented Programming Language Revised: Nov-2006@TW V0.5 OO 語言簡要 -Java 案例

The for Statement

• A for loop is functionally equivalent to the following while loop structure:

initialization;while ( condition ){ statement; increment;}

Page 86: Object-Oriented Programming Language Revised: Nov-2006@TW V0.5 OO 語言簡要 -Java 案例

The for Statement

• An example of a for loop:

• The initialization section can be used to declare a variable

• Like a while loop, the condition of a for loop is tested prior to executing the loop

• Therefore, the body of a for loop will execute zero or more times

for (int count=1; count <= 5; count++) System.out.println (count);

Page 87: Object-Oriented Programming Language Revised: Nov-2006@TW V0.5 OO 語言簡要 -Java 案例

The for Statement

• The increment section can perform any calculation

• A for loop is well suited for executing the body a specific number of times that can be calculated or determined in advance

for (int num=100; num > 0; num -= 5) System.out.println (num);

Page 88: Object-Oriented Programming Language Revised: Nov-2006@TW V0.5 OO 語言簡要 -Java 案例

The for Statement

• Each expression in a for statement is optional• If the initialization is left out, no initialization is

performed• If the condition is left out, it is always considered to

be true, and therefore creates an infinite loop• If the increment is left out, no increment operation

is performed• “Forever” can be written as:

for (;;) {body;}

Page 89: Object-Oriented Programming Language Revised: Nov-2006@TW V0.5 OO 語言簡要 -Java 案例

Continue and Break in Loops

• The break statement causes execution to “break” out of the repetitive loop execution (goes just outside the loop’s closing “}”)

• The continue statement causes execution to “continue” at the end of this pass of a loop (goes just inside the loop’s closing “}”)

Page 90: Object-Oriented Programming Language Revised: Nov-2006@TW V0.5 OO 語言簡要 -Java 案例

Method Declarations

• A method declaration specifies the code that will be executed when the method is invoked (called)

• When a method is invoked, the flow of control jumps to the method and executes its code

• When complete, the flow returns to the place where the method was called and continues

• The invocation may or may not return a value, depending on how the method is defined

Page 91: Object-Oriented Programming Language Revised: Nov-2006@TW V0.5 OO 語言簡要 -Java 案例

myMethod();

myMethodcompute

Method Control Flow• If the called method is in the same class, only the

method name is needed

Page 92: Object-Oriented Programming Language Revised: Nov-2006@TW V0.5 OO 語言簡要 -Java 案例

doIt

helpMe

helpMe();

obj.doIt();

main

Method Control Flow

• The called method is often part of another class or object

Page 93: Object-Oriented Programming Language Revised: Nov-2006@TW V0.5 OO 語言簡要 -Java 案例

Method Header

• A method declaration begins with a method header

char calc (int num1, int num2, String message)

methodname

returntype

parameter list

The parameter list specifies the typeand name of each parameter

The name of a parameter in the methoddeclaration is called a formal parameter

Page 94: Object-Oriented Programming Language Revised: Nov-2006@TW V0.5 OO 語言簡要 -Java 案例

Method Body

• The method header is followed by the method body

char calc (int num1, int num2, String message)

{ int sum = num1 + num2; char result = message.charAt (sum);

return result;}

The return expressionmust be consistent withthe return type

sum and resultare local data

They are created each time the method is called, and are destroyed when it finishes executing

Page 95: Object-Oriented Programming Language Revised: Nov-2006@TW V0.5 OO 語言簡要 -Java 案例

Local Data

• Local variables can be declared inside a method

• The formal parameters of a method are also local variables when the method is invoked

• When the method finishes, all local variables are destroyed (including the formal parameters)

• Keep in mind that instance variables, declared at the class/object level, exists as long as the object exists

Page 96: Object-Oriented Programming Language Revised: Nov-2006@TW V0.5 OO 語言簡要 -Java 案例

The return Statement

• The return type of a method indicates the type of value that the method sends back to the caller

• A method that does not return a value has a void return type

• A return statement specifies the value that will be returned upon completion of the method code

return expression;• Its expression must conform to the return type

Page 97: Object-Oriented Programming Language Revised: Nov-2006@TW V0.5 OO 語言簡要 -Java 案例

Parameters• When a method is called, the actual parameters

in the call are copied into the formal parameters in the method header

char calc (int num1, int num2, String message)

{ int sum = num1 + num2; char result = message.charAt (sum);

return result;}

ch = obj.calc (25, count, "Hello");

Page 98: Object-Oriented Programming Language Revised: Nov-2006@TW V0.5 OO 語言簡要 -Java 案例

Introduction to Classes

• A class has a name that we can use as if it were a data type when declaring a variable

• When we declare a variable with the name of a class as its type, we are creating an object variable (can contain a reference to an object)

• We access an object’s methods / attributes using the object variable name and the . notation, e.g. ClassName objectName; //object variable

objectName.methodName() // Note: The ( )

objectName.variableName // Note: No ( )

Page 99: Object-Oriented Programming Language Revised: Nov-2006@TW V0.5 OO 語言簡要 -Java 案例

Example of a Class Definition

• We can draw a diagram of a class to outline its important features before writing code – its name, attributes, and behaviors

StateMachine

- state :int. . .

+ setState (int input): void. . .

Class Name

List of itsVariables

List of itsMethods

Page 100: Object-Oriented Programming Language Revised: Nov-2006@TW V0.5 OO 語言簡要 -Java 案例

Example of a Class Definition

public class StateMachine {

// an attribute or variable

private int state;

// a behavior or method

public void setState (int input) {

state = input;

}

}

Page 101: Object-Oriented Programming Language Revised: Nov-2006@TW V0.5 OO 語言簡要 -Java 案例

Constructors

• A constructor is a special method that is used to set up an object when it is initially created

• A constructor has the same name as the class with no return type

• The Xxyz constructor is used to set the initial face value of each new die object to one

• We examine constructors in more detail later• 程式碼 : (Java/Javascript – new 運算子 )

Page 102: Object-Oriented Programming Language Revised: Nov-2006@TW V0.5 OO 語言簡要 -Java 案例

Encapsulation

• We can take one of two views of an object:– internal - the details of the variables and methods

of the class that defines it– external - the services that an object provides and

how the object interacts with the rest of the system

• From the external viewpoint, an object is an encapsulated entity providing a set of specific services

• These services define the interface to the object

Page 103: Object-Oriented Programming Language Revised: Nov-2006@TW V0.5 OO 語言簡要 -Java 案例

Encapsulation

• One object (called the client) may use another object for the services it provides

• The client of an object may request its services (call its methods), but it should not have to be aware of how those services are accomplished

• Any changes to the object's state (its variables) should be made by that object's methods

• We should make it difficult, if not impossible, for a client to access an object’s variables directly

• That is, an object should be self-governing

Page 104: Object-Oriented Programming Language Revised: Nov-2006@TW V0.5 OO 語言簡要 -Java 案例

Encapsulation

• An object can be thought of as a black box -- its inner workings are encapsulated or hidden from the client

• The client invokes the interface methods of the object, which manages the instance data

Methods

Data

Client

Page 105: Object-Oriented Programming Language Revised: Nov-2006@TW V0.5 OO 語言簡要 -Java 案例

Interfaces

public interface Doable{ public void doThis(); public int doThat(); public void doThis2 (float value, char ch); public boolean doTheOther (int num);}

interface is a reserved wordNone of the methods inan interface are given

a definition {body}

A semicolon immediatelyfollows each method header

Page 106: Object-Oriented Programming Language Revised: Nov-2006@TW V0.5 OO 語言簡要 -Java 案例

Interfaces• An interface cannot be instantiated by itself• A class implements an interface by:

– using the Java reserved word implements– providing an implementation for each abstract

method that is defined in the interface

• If a class definition says that it implements an interface, it must implement all methods defined in the interface

• Classes that implement an interface can also implement their own methods and they usually do

Page 107: Object-Oriented Programming Language Revised: Nov-2006@TW V0.5 OO 語言簡要 -Java 案例

Interfacespublic class CanDo implements Doable{ public void doThis () { // whatever }

public int doThat () { // whatever }

// etc.}

implements is areserved word

Each method listedin Doable must begiven a definition

Page 108: Object-Oriented Programming Language Revised: Nov-2006@TW V0.5 OO 語言簡要 -Java 案例

Interfaces In UML notation

CanDo

<<interface>> Doable

+ doThis( ) : void+ doThat( ) : int+ doThis2 (value : float, ch char) void+ doTheOther(num : int) : boolean

+ doThis( ) : void+ doThat( ) : int+ doThis2 (value : float, ch char) :void+ doTheOther(num : int) : boolean+ doNothing ( ) : void+ doSomething ( ) : void

Each method listedin Doable becomes a method of CanDo

CanDo can haveother methods

of its own

A “Generalization” arrowis used for “implements”(and also for “extends”)

Interface box looks likea class box with

stereotype <<interface>>

Page 109: Object-Oriented Programming Language Revised: Nov-2006@TW V0.5 OO 語言簡要 -Java 案例

Iterable Objects and Iterators

• An Iterable object allows you obtain an Iterator to retrieve objects from a group

• An Iterator is an object that allows you to retrieve a sequence of objects from a group using two methods:boolean hasNext() returns true if there are

more objects available from the Iterator

Object next() returns the next object

Page 110: Object-Oriented Programming Language Revised: Nov-2006@TW V0.5 OO 語言簡要 -Java 案例

Iterable Objects and Iterators

• Several classes in the Java standard class library are Iterable and/or Iterators

• For example, bookList may be an object of an Iterable class or of an Iterator class

• We can retrieve all the available Books in either of two ways depending on whether bookList is an Iterable object or is an Iterator

Page 111: Object-Oriented Programming Language Revised: Nov-2006@TW V0.5 OO 語言簡要 -Java 案例

Iterable Objects/Iterators and Loops• You can obtain an Iterator object from an

Iterable object and use it to retrieve all the items from the Iterable object indirectly:

• You can process all the items available from an Iterator object directly

while (bookList.hasNext())System.out.println (bookList.next());

Iterator itr = bookList.iterator();while (itr.hasNext())

System.out.println (itr.next());

Page 112: Object-Oriented Programming Language Revised: Nov-2006@TW V0.5 OO 語言簡要 -Java 案例

Iterable Objects and for Loops

• A (new in Java 5.0) variant of the for loop simplifies the repetitive processing of the items available from an Iterable object

• This type of loop has been brought into Java from other languages like PERL and can be read as “for each Book in bookList, …”

• This style of for loop can NOT be used with an Iterator object, e.g. a Scanner object

for (Book myBook : bookList) System.out.println (myBook);

Page 113: Object-Oriented Programming Language Revised: Nov-2006@TW V0.5 OO 語言簡要 -Java 案例

Part-3: Applications

•Problem-Solving Procedure

•Solving Quadratic Equations

Page 114: Object-Oriented Programming Language Revised: Nov-2006@TW V0.5 OO 語言簡要 -Java 案例

The Math Class

• The Math class is part of the java.lang package

• The Math class contains methods that perform various mathematical functions

• These include:

– absolute value

– square root

– exponentiation

– trigonometric functions

Page 115: Object-Oriented Programming Language Revised: Nov-2006@TW V0.5 OO 語言簡要 -Java 案例

The Math Class

• The methods of the Math class are static methods (also called class methods)

• Static methods can be invoked through the class name – no object of the Math class is needed

value = Math.cos(90) + Math.sqrt(delta);

• Similar to Quadratic.java (page 129)discriminant = Math.pow(b, 2) – 4.0 * a * c;

root1 = (-1.0 * b + Math.sqrt(discriminant))/(2.0 * a);

root2 = (-1.0 * b – Math.sqrt(discriminant))/(2.0 * a);

• Note: We can’t program the + in the formula on page 130 in Java. We need to calculate each root separately

Page 116: Object-Oriented Programming Language Revised: Nov-2006@TW V0.5 OO 語言簡要 -Java 案例

Solving Quadratic Equations

• However, the textbook’s program to solve for the roots of a quadratic equation is deficient!

• The equations for calculating the roots are correct but are not used correctly in the program

• Since the user can enter any combination of three integer values for the coefficients, we need to analyze the possible special cases where just computing the formula based on the input values of “a”, “b”, and “c” is not correct

• This is the introduction to your Project #1

Page 117: Object-Oriented Programming Language Revised: Nov-2006@TW V0.5 OO 語言簡要 -Java 案例

Solving Quadratic Equations

• User can enter any values for “a”, “b”, and “c”

• If the user enters values that cannot be computed properly using the formulas, the program will fail to operate correctly

• Let’s try a = 1, b = 0, and c = 1

• The program generates two answers– NaN stands for “Not a Number”

• What happened?

Page 118: Object-Oriented Programming Language Revised: Nov-2006@TW V0.5 OO 語言簡要 -Java 案例

Solving Quadratic Equations

• With those coefficient values, the formula for calculating the discriminant results in a negative numberdiscriminant = Math.pow(b, 2) – 4.0 * a * c;

discriminant = Math.pow(0, 2) – 4.0 * 1 * 1;

discriminant = -4.0;

• Later in calculating the roots, the formula takes the square root of the discriminant

• Mathematically, a negative number does not have a “real” square root

Page 119: Object-Oriented Programming Language Revised: Nov-2006@TW V0.5 OO 語言簡要 -Java 案例

Solving Quadratic Equations

• The Math.sqrt() method can’t provide any “real” number that is the square root of -4.0

• In this case, it returns the result “NaN”• However, in algebra we learned to “fake” the

square root of a negative number by using the “imaginary” number i (the square root of -1)Math.sqrt(-4.0) can be shown as:Math.sqrt(-1 * 4.0) which equals:Math.sqrt(-1) * Math.sqrt(4.0) which equals:i * 2.0 where i is the “imaginary” square root of -1

• How can we get our program to print this answer?

Page 120: Object-Oriented Programming Language Revised: Nov-2006@TW V0.5 OO 語言簡要 -Java 案例

Solving Quadratic Equations

• We need to write the program so that our code checks the value of the discriminant before trying to take the square root of it

• If the value of the discriminant is negative, we need to construct the correct answer= “i * ” + Math.sqrt(Math.abs(-4.0));

• That code will provide the resulting String= “i * 2.0”

Page 121: Object-Oriented Programming Language Revised: Nov-2006@TW V0.5 OO 語言簡要 -Java 案例

Solving Quadratic Equations

• There are other possible values of “a”, “b”, and “c” that can result in NaN or no valid result

• Suppose the user enters a value of 0 for “a”?• The formula for the roots divides by (2.0 * a)• If the value of “a” is 0, the division is impossible• The expression evaluations will provide the

results NaN or –Infinity• Again, we need to write the program so that our

code checks the value of “a” before trying to do the division

Page 122: Object-Oriented Programming Language Revised: Nov-2006@TW V0.5 OO 語言簡要 -Java 案例

Solving Quadratic Equations

• If the value of “a” is 0, is there a solution?• Yes, let’s look at the equation with “a” = 0

0 * Math.pow(x, 2) + b * x + c = 0 is the same as:b * x + c = 0 which can be solved as a linear equation:x = - c / b as long as b is not equal to 0!Note: There is now only one root - not two

• Based on the above, we can see another special case, if “b” is equal to 0 (but only if “a” is also equal to 0)

• It is OK for “b” to be equal to 0, if “a” is not 0

Page 123: Object-Oriented Programming Language Revised: Nov-2006@TW V0.5 OO 語言簡要 -Java 案例

Solving Quadratic Equations

• Suppose both “a” = 0 and “b” = 0?• The remaining equation looks like this:

0 + 0 + c = 0

• If the user entered a value of 0 for “c”, then any value of x is a solution, i.e. 0 + 0 + 0 always = 0

• But, suppose the user had entered a value for “c” that was not equal to 0?

• Now, there is no possible solution for x• No value of x can make a non-zero value of “c” be

equal to 0

Page 124: Object-Oriented Programming Language Revised: Nov-2006@TW V0.5 OO 語言簡要 -Java 案例

Solving Quadratic Equations

• Now that we have covered all these cases, what does it mean for our programming of a program for solving quadratic equations based on values for “a”, “b”, and “c”?

• We need to write the program so that our code makes decisions about each of these possible special cases before just trying to calculate a result based on the formulas

Page 125: Object-Oriented Programming Language Revised: Nov-2006@TW V0.5 OO 語言簡要 -Java 案例

Control Flow

• Up until now, all of our programs just ran sequentially through a sequence of steps

• Each statement did something and then continued to the next statement in sequence

• To make decisions while solving a quadratic equation, we need to control the flow of the execution of statements in our program

• We will see how to do that in the next lecture

Page 126: Object-Oriented Programming Language Revised: Nov-2006@TW V0.5 OO 語言簡要 -Java 案例

Factoring our Program

• But before we do that, let’s see how to divide our program into smaller parts

• This is called factoring the program• If we think about it, we can envision two

different things that our program has to do– Gather input from the user and display results– Calculate the results based on the formulas

• At a top level, we can create one class for each of those two parts of the problem

Page 127: Object-Oriented Programming Language Revised: Nov-2006@TW V0.5 OO 語言簡要 -Java 案例

Factoring our Program

• Why would we want to break our program down into two parts or classes?

• There are many possible reasons, two are:– We may assign two programmers to the job

Each programmer can write one of the classes– We may be able to reuse one part separately

from the other part, e.g. use the calculation class with a CLI class initially and re-use it later with a GUI class to make it more “user friendly”

Page 128: Object-Oriented Programming Language Revised: Nov-2006@TW V0.5 OO 語言簡要 -Java 案例

Factoring our Program

• Proposed “class diagram” for our program: QuadraticCLI

QuadraticSolver

+ main(String [ ]): void

A dotted arrow means that theQuadraticCLI class “dependson” the QuadraticSolver class

Remember that oneof our classes musthave a main method

Page 129: Object-Oriented Programming Language Revised: Nov-2006@TW V0.5 OO 語言簡要 -Java 案例

The QuadraticCLI Class• Passing the inputs to the QuadraticSolver class

Scanner scan = new Scanner(System.in);QuadraticSolver mySolver = new QuadraticSolver();

System.out.println(“Enter coefficient A”);mySolver.setA(scan.nextInt());System.out.println(“Enter coefficient B”);mySolver.setB(scan.nextInt());System.out.println(“Enter coefficient C”);mySolver.setC(scan.nextInt());

// we have the data to solve the equationSystem.out.println(mySolver.getEquation());System.out.println(mySolver.getSolution());

Page 130: Object-Oriented Programming Language Revised: Nov-2006@TW V0.5 OO 語言簡要 -Java 案例

The QuadraticSolver Class• Declaration of the QuadraticSolver variables

private int a;private int b;private int c;

• These variables are can only be access from code in methods of the QuadraticSolver class

• The Java reserved word private ensures that these variables cannot be accessed from any code outside the QuadraticSolver class

• The Java reserved word public allows access to the methods on the next slide from code outside the QuadraticSolver class

• These types of public methods are called mutators and they each assign a value to a private variable

Page 131: Object-Oriented Programming Language Revised: Nov-2006@TW V0.5 OO 語言簡要 -Java 案例

The QuadraticSolver Class

• Methods allowing the QuadraticCLI class to set the coefficients for the equation to be solved:

public void setA(int input) {a = input;

}public void setB(int input) {b = input;

}public void setC(int input) {c = input;

}

Page 132: Object-Oriented Programming Language Revised: Nov-2006@TW V0.5 OO 語言簡要 -Java 案例

The QuadraticSolver Class

• A method that provides the solution as a String

public String getSolution() {String solution;

// use the formulas to create// a solution String that can be// displayed to the user by the// QuadraticCLI class. . .return solution;

}

Page 133: Object-Oriented Programming Language Revised: Nov-2006@TW V0.5 OO 語言簡要 -Java 案例

Classes, Encapsulation, Methods and Constructors (Continued)

• Class definitions• Instance data• Encapsulation and Java modifiers• Method declaration and parameter

passing• Constructors• Javadoc

Page 134: Object-Oriented Programming Language Revised: Nov-2006@TW V0.5 OO 語言簡要 -Java 案例

案例 : Bank Account Example

• Let’s look at another example that demonstrates implementation details of classes and methods

• We’ll represent a bank account by a class named Account

• It’s state can include the account number, the current balance, and the name of the owner

• An account’s behaviors (or services) include deposits and withdrawals, and adding interest

Page 135: Object-Oriented Programming Language Revised: Nov-2006@TW V0.5 OO 語言簡要 -Java 案例

Driver Programs

• A driver program drives the use of other parts of a program

• Driver programs are often used to test other parts of the software

• The Transactions class contains a main method that drives the use of the Account class, exercising its services

• See Transactions.java (page 172)• See Account.java (page 173)

Page 136: Object-Oriented Programming Language Revised: Nov-2006@TW V0.5 OO 語言簡要 -Java 案例

Bank Account Exampleacct1 72354acctNumber

102.56balance

name “Ted Murphy”

acct2 69713acctNumber

40.00balance

name “Jane Smith”

Page 137: Object-Oriented Programming Language Revised: Nov-2006@TW V0.5 OO 語言簡要 -Java 案例

Bank Account Example

• There are some improvements that can be made to the Account class

• Formal getters and setters could have been defined for all data

• The design of some methods could also be more robust, such as verifying that the amount parameter to the withdraw method is positive

Page 138: Object-Oriented Programming Language Revised: Nov-2006@TW V0.5 OO 語言簡要 -Java 案例

Optional Reading

Page 139: Object-Oriented Programming Language Revised: Nov-2006@TW V0.5 OO 語言簡要 -Java 案例

Constructors Revisited

• Note that a constructor has no return type specified in the method header, not even void

• A common error is to put a return type on a constructor, which makes it a “regular” method that happens to have the same name as the class

• The programmer does not have to define a constructor for a class

• Each class has a default constructor that accepts no parameters

Page 140: Object-Oriented Programming Language Revised: Nov-2006@TW V0.5 OO 語言簡要 -Java 案例

Javadoc• Javadoc is a JDK tool that creates HTML

user documentation for your classes and their methods

• In this case, user means a programmer who will be writing Java code using your classes

• You can access Javadoc via the JDK CLI:> javadoc MyClass.java

• You can access Javadoc via Dr Java menu: Tools > Javadoc All DocumentsTools > Preview Javadoc for Current Document

Page 141: Object-Oriented Programming Language Revised: Nov-2006@TW V0.5 OO 語言簡要 -Java 案例

Javadoc

• The Javadoc tool scans your source file for specialized multi-line style comments:/**

* <p>HTML formatted text here</p>

*/

• Your Javadoc text is written in HTML so that it can appear within a standardized web page format

Page 142: Object-Oriented Programming Language Revised: Nov-2006@TW V0.5 OO 語言簡要 -Java 案例

Block Tags for Classes

• At the class level, you must include these block tags with data (each on a separate line):/**

* @author Your Name

* @version Version Number/Date

*/

• You should include HTML text describing the use of this class and perhaps give examples

Page 143: Object-Oriented Programming Language Revised: Nov-2006@TW V0.5 OO 語言簡要 -Java 案例

Block Tags for Methods

• At the method level, you must include these block tags with data (each on a separate line):/** * @param HTML text for 1st parameter

* @param HTML text for 2nd parameter * @return HTML text for return value */

• If there are no parameters or return type, you can omit those Javadoc block tags

Page 144: Object-Oriented Programming Language Revised: Nov-2006@TW V0.5 OO 語言簡要 -Java 案例

In Line Tags

• At any point in your Javadoc HTML text, you may use In-Line Tags such as @link:/**

* <p>See website {@link name url}

* for more details.</p>

*/