An Object-Oriented Approach to

processroguishΛογισμικό & κατασκευή λογ/κού

18 Νοε 2013 (πριν από 3 χρόνια και 4 μήνες)

73 εμφανίσεις

An Object
-
Oriented Approach to
Programming Logic and Design

Third Edition

Chapter 2

Working with Classes, the Main
Method, and Data

An Object
-
Oriented Approach to Programming Logic and Design

2

Objectives

In this chapter, you will learn about:


Creating an application class with a
main()
method


Using literals, variables, and named constants


Assigning values to variables


Arithmetic operations


Some features of good program design


Structure and creating a complete program

An Object
-
Oriented Approach to Programming Logic and Design

3

Creating an Application Class with a
main()
Method


Application


Program that executes to accomplish a task


Method


Named set of statements that perform task(s) in an
application


If application has only one method, it is called the
main method

An Object
-
Oriented Approach to Programming Logic and Design

4

Creating an Application Class with a
main()

Method (cont’d.)

Figure 2
-
1

Flowchart and pseudocode for a class with a
main()

method that prints “Hello’

An Object
-
Oriented Approach to Programming Logic and Design

5

Creating an Application Class with a
main()

Method


Begins with word
class

followed by the class
name


Ends with word
endClass


No object
-
oriented programming language uses
endClass


Used here to emphasize where class ends


Class header and ending statement aligned
vertically for easy reading


Only one header and one
endClass

statement for
each class

An Object
-
Oriented Approach to Programming Logic and Design

6

Creating an Application Class with a
main()

Method (cont’d.)


Identifier


Name of programming object (class, method, or
variable)


Different programming languages have different rules
for naming identifiers

An Object
-
Oriented Approach to Programming Logic and Design

7

Creating an Application Class with a
main()

Method (cont’d.)


Examples of identifier rules


Can contain letters and digits


Some languages allow special characters


May not begin with a digit (most languages)


May not contain white space (spaces, tabs, line
breaks)


May not be a keyword


Are case sensitive (
Hello
,
hello
, and
HELLO

are all
separate identifiers)


Descriptive names are best

An Object
-
Oriented Approach to Programming Logic and Design

8

Understanding the
main()

Method


Classes that contain a
main()

method are
executable programs


Set of parentheses always follows method name


Method identifiers follow same basic rules as class
identifiers


Convention of this book: begin method names with a
lowercase letter and end the method with a return
statement


The method’s executable statements are placed
between method header and return statement

An Object
-
Oriented Approach to Programming Logic and Design

9

Understanding the
main()

Method
(cont’d.)


Subsequent words in a method header are
capitalized for readability


Examples:
computePaycheck
,
startTheGame


Pseudocode indentation conventions


Method header and return statement align vertically to
show they are a pair


Method statements are indented more than
class

and
endClass

statements but less than executable
statements in code

An Object
-
Oriented Approach to Programming Logic and Design

10

Understanding How Programming
Languages Reflect Logic

Figure 2
-
2

The
Hello

class written in the Java programming language

Figure 2
-
3

The
Hello

class written in the C# programming language

An Object
-
Oriented Approach to Programming Logic and Design

11

Understanding How Programming
Languages Reflect Logic (cont’d.)

Figure 2
-
4

The
Hello

class written in the Visual Basic programming language

An Object
-
Oriented Approach to Programming Logic and Design

12

Using Literals, Variables, and Named
Constants


Data can be input in different ways


User enters data in an interactive program


Storage devices provide data in batch programs


Data is stored in memory variables


Three different forms of data


Literals (unnamed constants)


Variables


Named constants

An Object
-
Oriented Approach to Programming Logic and Design

13

Understanding Unnamed, Literal Constants
and Their Data Types


Two types of unnamed data: numeric and text


Literal numeric constant


Number without quotation marks


Example:
43


Cannot contain alphabetic characters


String constant, or literal string constant


Text enclosed in quotation marks


Example:
“Amanda”


Also called alphanumeric


Can contain digits, punctuation, and other characters

An Object
-
Oriented Approach to Programming Logic and Design

14

Working with Variables


Variables


Named memory locations


Contents can vary over time


Hold just one value at any given time


Before a variable can be used, it must be declared
(most programming languages)


Variable declaration includes data type and identifier

An Object
-
Oriented Approach to Programming Logic and Design

15

Working with Variables (cont’d.)

Figure 2
-
5

Statements that input a number, double it, and display the results


Example of a variable declaration

An Object
-
Oriented Approach to Programming Logic and Design

16

Working with Variables (cont’d.)


Data type is classification describing:


What values it can hold


How it is stored in memory


What operations can be performed on it


In this book, two data types are used


num


string


An Object
-
Oriented Approach to Programming Logic and Design

17

Working with Variables (cont’d.)


Initializing the variable


Provide a starting value for the variable


If a variable is declared but not initialized


The intention is to assign a value later


The variable contains unknown value called garbage


In many programming languages, it is illegal to use a
garbage
-
holding variable or display it as output


An Object
-
Oriented Approach to Programming Logic and Design

18

Naming Variables


Choose descriptive, meaningful names


Interpreter associates names with specific memory
addresses


Variable naming follows same rules as naming
classes and methods


An Object
-
Oriented Approach to Programming Logic and Design

19

Understanding a Variable’s Data Type


Numeric variable


Holds digits and can have mathematical operations
performed on it


Can hold a decimal point and a sign (plus or minus)


String variable


Holds text (letters of alphabet) and special characters


Can hold digits but cannot do mathematical
operations on them


Examples:
lastname=“Lincoln”
,
“235 Main
St.”
,
“86”


An Object
-
Oriented Approach to Programming Logic and Design

20

Understanding a Variable’s Data Type
(cont’d.)


Can assign data to a variable only if correct type


Examples:

num taxRate

taxRate = 2.5


OK


taxRate = “2.5”


invalid


Can set a variable to the value of another
variable of the same data type


An Object
-
Oriented Approach to Programming Logic and Design

21

Declaring Named Constants


Named constant is assigned value only once


Used to identify values that will not be changed
during program execution


Example:
SALES_TAX


This book’s convention


All uppercase letters, with underscore separating
words for readability

An Object
-
Oriented Approach to Programming Logic and Design

22

Declaring Named Constants (cont’d.)


Benefits of using named constants


Ease of program maintenance


Change value once and all references change
automatically


Naming provides type of documentation


Helps prevent typographical errors

An Object
-
Oriented Approach to Programming Logic and Design

23

Assigning Values to Variables


Assignment statement


Example:
myAnswer = myNumber * 2


Makes the calculation


Stores the result in the
myAnswer

memory
location


Assignment operator (equal sign)


Always operates from right to left


Right side is evaluated before the assignment is
made


Value to the left must be a memory address


An Object
-
Oriented Approach to Programming Logic and Design

24

Performing Arithmetic Operations


Standard arithmetic operators

+

(plus sign)


addition

-

(minus sign)


subtraction

*

(asterisk)


multiplication

/

(slash)


division

An Object
-
Oriented Approach to Programming Logic and Design

25

Performing Arithmetic Operations
(cont’d.)


Rules of precedence


The order of arithmetic operations in a given
statement


Parentheses evaluated first


Multiplication and division next, left to right


Addition and subtraction next, left to right


Forgetting about rules of precedence results in
logical errors that may be difficult to find


Extra parentheses may be used for clarity

An Object
-
Oriented Approach to Programming Logic and Design

26

Performing Arithmetic Operations
(cont’d.)

Table 2
-
1
Precedence and associativity of five common operators

An Object
-
Oriented Approach to Programming Logic and Design

27

Features of Good Program Design


Good practices that make programs easier to write
and maintain


Use comments where appropriate


Choose meaningful identifiers


Strive to design clear statements


Write clear prompts and echo input


Maintain good programming habits as skills improve

An Object
-
Oriented Approach to Programming Logic and Design

28

Using Program Comments


Purpose of comments


Aid in identifying the purpose of variables


Explain complex calculations


Allow a new programmer to understand existing code


Comments more useful in program code than in
flowcharts or pseudocode

An Object
-
Oriented Approach to Programming Logic and Design

29

Choosing Identifiers


General guidelines


Variables or constants should be named with nouns
or combination of nouns and adjectives


Methods should be named with verbs or combined
verb and noun


Use meaningful names (self
-
documenting)


Use pronounceable names


Use abbreviations sparingly


An Object
-
Oriented Approach to Programming Logic and Design

30

Choosing Identifiers (cont’d.)


General guidelines (cont’d.)


Avoid digits in a name


Separate words in long, multiword identifiers


For variables that hold status, use a form of the verb
“to be” such as “is” or “are”


Constants in all uppercase with underscores between
words


Different conventions may be dictated by the
organization


An Object
-
Oriented Approach to Programming Logic and Design

31

Designing Clear Statements


Avoid confusing line breaks


Most languages are free
-
form: make sure meaning is
clear


Use temporary variables to clarify long statements


Temporary variable is an intermediate, or work
variable


Not used for input or output


Used during program execution


An Object
-
Oriented Approach to Programming Logic and Design

32

Designing Clear Statements (cont’d.)


Example of using temporary variables

Figure 2
-
6
Two ways of achieving the same
salespersonCommission

result

An Object
-
Oriented Approach to Programming Logic and Design

33

Writing Clear Prompts and Echoing Input


Prompts: messages that ask user for response


Used in command line and GUI interactive programs


Not needed if input comes from a file


Echoing input


Repeating input back to the user in a prompt or output


Useful as an aid in identifying input errors

An Object
-
Oriented Approach to Programming Logic and Design

34

Designing Clear Statements (cont’d.)


Example of using prompts and echoing input

Figure 2
-
9
Beginning of a program that accepts a customer’s name and uses it in
the second prompt

An Object
-
Oriented Approach to Programming Logic and Design

35

An Introduction to Structure and Creating
a Complete Program


Structure


Basic unit of programming logic


Three structures: sequence, selection,
and loop


Sequence structure


Perform one action after another with
no decision points


Perform all steps until the sequence
ends


Example: driving directions


Figure 2
-
10
The
sequence structure

An Object
-
Oriented Approach to Programming Logic and Design

36

An Introduction to Structure and Creating
a Complete Program (cont’d.)


Selection structure


One of two branches of logic is followed, based on a
decision


Loop structure


Instructions repeat, based on a decision


Figure 2
-
11
The selection structure

Figure 2
-
12
The loop structure

An Object
-
Oriented Approach to Programming Logic and Design

37

Figure 2
-
13
Flowchart of the
N
etPayCalculator
application class

An Object
-
Oriented Approach to Programming Logic and Design

38

Summary


Application is a program that accomplishes a task


Method is a set of statements that performs tasks in
an application; one example is the
main()

method


Classes and methods must have identifiers


Data values are stored as literals, variables, and
named constants


Can be numeric or string


Variables are named memory locations with
contents that can differ over time


An Object
-
Oriented Approach to Programming Logic and Design

39

Summary (cont’d.)


Data type is classification that describes values that
can be held


Declaration statement provides the data type and
identifier for a variable


Named constant can be assigned a value only once


Equal sign is the assignment operator


Four standard arithmetic operators (
+
,
-
,
*
,
/
)


Rules of precedence dictate order of arithmetic
operations



An Object
-
Oriented Approach to Programming Logic and Design

40

Summary (cont’d.)


Examples of good programming practices


Including appropriate comments


Choose identifiers wisely


Design clear statements


Write clear prompts and echo input


Structure is term for basic unit of programming logic


Sequence, selection, and loop