presentation slides for java software...

212
Presentation slides for J J a a v v a a S S o o f f t t w w a a r r e e S S o o l l u u t t i i o o n n s s Foundations of Program Design Second Edition by John Lewis and William Loftus Part I (chapters 1 – 5) Prepared for Java Programming 90.301 by Marjan Trutschl [email protected]

Upload: dinhque

Post on 20-Mar-2018

228 views

Category:

Documents


3 download

TRANSCRIPT

Page 1: Presentation slides for Java Software Solutionsmtrutsch/teaching/class/90301/HandoutAllSlides...Presentation slides for Java Software Solutions ... Presentation slides for Java Software

PPrreesseennttaattiioonn sslliiddeess ffoorr

JJaavvaa SSooffttwwaarree SSoolluuttiioonnssFFoouunnddaattiioonnss ooff PPrrooggrraamm DDeessiiggnn

SSeeccoonndd EEddiittiioonn

bbyy JJoohhnn LLeewwiiss aanndd WWiilllliiaamm LLooffttuuss

PPaarrtt II((cchhaapptteerrss 11 –– 55))

PPrreeppaarreedd ffoorr JJaavvaa PPrrooggrraammmmiinngg 9900..330011bbyy MMaarrjjaann TTrruuttsscchhll

mmttrruuttsscchh@@ccss..uummll..eedduu

Page 2: Presentation slides for Java Software Solutionsmtrutsch/teaching/class/90301/HandoutAllSlides...Presentation slides for Java Software Solutions ... Presentation slides for Java Software
Page 3: Presentation slides for Java Software Solutionsmtrutsch/teaching/class/90301/HandoutAllSlides...Presentation slides for Java Software Solutions ... Presentation slides for Java Software

1

Chapter 1: Computer Systems

Presentation slides for

Java Software SolutionsFoundations of Program Design

Second Edition

by John Lewis and William Loftus

Java Software Solutions is published by Addison-Wesley

Presentation slides are copyright 2000 by John Lewis and William Loftus. All rights reserved.Instructors using the textbook may use and modify these slides for pedagogical purposes.

2

Focus of the Course

b Object-Oriented Software Development

• problem solving

• program design and implementation

• object-oriented concepts– objects

– classes

– interfaces

– inheritance

– polymorphism

• graphics and Graphical User Interfaces

• the Java programming language

Page 4: Presentation slides for Java Software Solutionsmtrutsch/teaching/class/90301/HandoutAllSlides...Presentation slides for Java Software Solutions ... Presentation slides for Java Software

2

3

Computer Systems

b We first need to explore the fundamentals of computerprocessing

b Chapter 1 focuses on:• components of a computer

• how those components interact

• how computers store and manipulate information

• computer networks

• the Internet and the World-Wide Web

• programming and programming languages

• graphic systems

4

Hardware and Software

b Hardware• the physical, tangible parts of a computer

• keyboard, monitor, wires, chips, data

b Software• programs and data

• a program is a series of instructions

b A computer requires both hardware and software

b Each is essentially useless without the other

Page 5: Presentation slides for Java Software Solutionsmtrutsch/teaching/class/90301/HandoutAllSlides...Presentation slides for Java Software Solutions ... Presentation slides for Java Software

3

5

CPU and Main Memory

CentralProcessing

Unit

MainMemory

Chip that executesprogram commands

Intel Pentium IIISun Sparc Processor

Primary storage areafor programs and data

that are in active use

Synonymous withRAM

6

Secondary Memory Devices

Floppy Disk

Hard DiskMain

Memory

CentralProcessing

Unit

Secondary memorydevices providelong-term storage

Information is movedbetween main memoryand secondary memoryas needed

Hard disksFloppy disksZIP disksWritable CDsTapes

Page 6: Presentation slides for Java Software Solutionsmtrutsch/teaching/class/90301/HandoutAllSlides...Presentation slides for Java Software Solutions ... Presentation slides for Java Software

4

7

Input / Output Devices

Monitor

Keyboard

MainMemory

CentralProcessing

Unit

Floppy Disk

Hard Disk

I/O devices allow userinteraction

Monitor screenKeyboardMouseBar code scannerLight penTouch screen

8

Software Categories

b Operating System• controls all machine activities

• provides the user interface to the computer

• manages resources such as the CPU and memory

• Windows 98, Windows NT, Unix, Linux, Mac OS

b Application program• generic term for any other kind of software

• word processors, missile control systems, games

b Most operating systems and application programs have agraphical user interface (GUI)

Page 7: Presentation slides for Java Software Solutionsmtrutsch/teaching/class/90301/HandoutAllSlides...Presentation slides for Java Software Solutions ... Presentation slides for Java Software

5

9

Analog vs. Digital

b There are two basic ways to store and manage data:

b Analog• continuous, in direct proportion to the data represented

• music on a record album - a needle rides on ridges in the groovesthat are directly proportional to the voltage sent to the speaker

b Digital• the information is broken down into pieces, and each piece is

represented separately

• music on a compact disc - the disc stores numbers representingspecific voltage levels sampled at various points

10

Digital Information

b Computers store all information digitally:• numbers

• text

• graphics and images

• audio

• video

• program instructions

b In some way, all information is digitized - broken down intopieces and represented as numbers

Page 8: Presentation slides for Java Software Solutionsmtrutsch/teaching/class/90301/HandoutAllSlides...Presentation slides for Java Software Solutions ... Presentation slides for Java Software

6

11

Representing Text Digitally

b For example, every character is stored as a number,including spaces, digits, and punctuation

b Corresponding upper and lower case letters are separatecharacters

H i , H e a t h e r .

72 105 44 32 72 101 97 116 104 101 114 46

12

Binary Numbers

b Once information is digitized, it is represented and storedin memory using the binary number system

b A single binary digit (0 or 1) is called a bit

b Devices that store and move information are cheaper andmore reliable if they only have to represent two states

b A single bit can represent two possible states, like a lightbulb that is either on (1) or off (0)

b Combinations of bits are used to store values

Page 9: Presentation slides for Java Software Solutionsmtrutsch/teaching/class/90301/HandoutAllSlides...Presentation slides for Java Software Solutions ... Presentation slides for Java Software

7

13

Bit Combinations

1 bit

01

2 bits

00011011

3 bits

000001010011100101110111

4 bits

00000001001000110100010101100111

10001001101010111100110111101111

Each additional bit doubles the number of possible combinations

14

Bit Combinations

b Each combination can represent a particular item

b There are 2N combinations of N bits

b Therefore, N bits are needed to represent 2N unique items

21 = 2 items

22 = 4 items

23 = 8 items

24 = 16 items

25 = 32 items

1 bit ?

2 bits ?

3 bits ?

4 bits ?

5 bits ?

How manyitems can be

represented by

Page 10: Presentation slides for Java Software Solutionsmtrutsch/teaching/class/90301/HandoutAllSlides...Presentation slides for Java Software Solutions ... Presentation slides for Java Software

8

15

A Computer Specification

b Consider the following specification for a personalcomputer:

• 600 MHz Pentium III Processor

• 256 MB RAM

• 16 GB Hard Disk

• 24x speed CD ROM Drive

• 17” Multimedia Video Display with 1280 x 1024 resolution

• 56 KB Modem

b What does it all mean?

16

Memory

Main memory is dividedinto many memorylocations (or cells)

927892799280928192829283928492859286

Each memory cell has anumeric address, whichuniquely identifies it

Page 11: Presentation slides for Java Software Solutionsmtrutsch/teaching/class/90301/HandoutAllSlides...Presentation slides for Java Software Solutions ... Presentation slides for Java Software

9

17

Storing Information

927892799280928192829283928492859286

Large values arestored in consecutivememory locations

10011010Each memory cell stores aset number of bits (usually8 bits, or one byte)

18

Storage Capacity

b Every memory device has a storage capacity, indicating thenumber of bytes it can hold

b Capacities are expressed in various units:

KB 210 = 1024

MB 220 (over 1 million)

GB 230 (over 1 billion)

TB 240 (over 1 trillion)

Unit Symbol Number of Bytes

kilobyte

megabyte

gigabyte

terabyte

Page 12: Presentation slides for Java Software Solutionsmtrutsch/teaching/class/90301/HandoutAllSlides...Presentation slides for Java Software Solutions ... Presentation slides for Java Software

10

19

Memory

b Main memory is volatile - stored information is lost if theelectric power is removed

b Secondary memory devices are nonvolatile

b Main memory and disks are direct access devices -information can be reached directly

b The terms direct access and random access are often usedinterchangeably

b A magnetic tape is a sequential access device since its data isarranged in a linear order - you must get by theintervening data in order to access other information

20

RAM vs. ROM

b RAM - Random Access Memory (direct access)

b ROM - Read-Only Memory

b The terms RAM and main memory are basicallyinterchangeable

b ROM could be a set of memory chips, or a separate device,such as a CD ROM

b Both RAM and ROM are random (direct) access devices!

b RAM should probably be called Read-Write Memory

Page 13: Presentation slides for Java Software Solutionsmtrutsch/teaching/class/90301/HandoutAllSlides...Presentation slides for Java Software Solutions ... Presentation slides for Java Software

11

21

The Central Processing Unit

b A CPU is also called a microprocessor

b It continuously follows the fetch-decode-execute cycle:

fetch

Retrieve an instruction from main memory

decode

Determine what theinstruction is

execute

Carry out theinstruction

22

The Central Processing Unit (CPU)

b The CPU contains:

Arithmetic / Logic Unit

Registers

Control Unit

Small storageareas

Performs calculationsand decisions

Coordinatesprocessing steps

Page 14: Presentation slides for Java Software Solutionsmtrutsch/teaching/class/90301/HandoutAllSlides...Presentation slides for Java Software Solutions ... Presentation slides for Java Software

12

23

The Central Processing Unit

b The speed of a CPU is controlled by the system clock

b The system clock generates an electronic pulse at regularintervals

b The pulses coordinate the activities of the CPU

b The speed is measured in megahertz (MHz)

24

Monitor

b The size of a monitor (17") is measured diagonally, like atelevision screen

b Most monitors these days have multimedia capabilities:text, graphics, video, etc.

b A monitor has a certain maximum resolution , indicatingthe number of picture elements, called pixels, that it candisplay (such as 1280 by 1024)

b High resolution (more pixels) produces sharper pictures

Page 15: Presentation slides for Java Software Solutionsmtrutsch/teaching/class/90301/HandoutAllSlides...Presentation slides for Java Software Solutions ... Presentation slides for Java Software

13

25

Modem

b Data transfer devices allow information to be sent andreceived between computers

b Many computers include a modem, which allowsinformation to be moved across a telephone line

b A data transfer device has a maximum data transfer rate

b A modem, for instance, may have a data transfer rate of56,000 bits per second (bps)

26

Networks

b A network is two or more computers that are connected sothat data and resources can be shared

b Most computers are connected to some kind of network

b Each computer has its own network address, which uniquelyidentifies it among the others

b A file server is a network computer dedicated to storingprograms and data that are shared among network users

Page 16: Presentation slides for Java Software Solutionsmtrutsch/teaching/class/90301/HandoutAllSlides...Presentation slides for Java Software Solutions ... Presentation slides for Java Software

14

27

Network Connections

b Each computer in a network could be directly connected toeach other computer in the network

b These are called point-to-point connections

This technique is not feasible formore than a few close machines

Adding a computer requiresa new communication linefor each computer alreadyin the network

28

Network Connections

b Most modern networks share a single communication line

b Adding a new computer to the network is relatively easy

Network traffic must taketurns using the line, whichintroduces delays

Often information is brokendown in parts, called packets,which are sent to the receivingmachine then reassembled

Page 17: Presentation slides for Java Software Solutionsmtrutsch/teaching/class/90301/HandoutAllSlides...Presentation slides for Java Software Solutions ... Presentation slides for Java Software

15

29

Local-Area Networks

LAN

A Local-Area Network(LAN) covers a smalldistance and a smallnumber of computers

A LAN often connects the machinesin a single room or building

30

Wide-Area Networks

LAN

A Wide-Area Network (WAN)connects two or more LANs,often over long distances

A LAN is usually ownedby one organization, buta WAN often connectsdifferent groups indifferent countries

LAN

Page 18: Presentation slides for Java Software Solutionsmtrutsch/teaching/class/90301/HandoutAllSlides...Presentation slides for Java Software Solutions ... Presentation slides for Java Software

16

31

The Internet

b The Internet is a WAN which spans the entire planet

b The word Internet comes from the term internetworking,which implies communication among networks

b It started as a United States government project, sponsoredby the Advanced Research Projects Agency (ARPA), andwas originally called the ARPANET

b The Internet grew quickly throughout the 1980s and 90s

b Less than 600 computers were connected to the Internet in1983; now there are over 10 million

32

TCP/IP

b A protocol is a set of rules that determine how thingscommunicate with each other

b The software which manages Internet communicationfollows a suite of protocols called TCP/IP

b The Internet Protocol (IP) determines the format of theinformation as it is transferred

b The Transmission Control Protocol (TCP) dictates howmessages are reassembled and handles lost information

Page 19: Presentation slides for Java Software Solutionsmtrutsch/teaching/class/90301/HandoutAllSlides...Presentation slides for Java Software Solutions ... Presentation slides for Java Software

17

33

IP and Internet Addresses

b Each computer on the Internet has a unique IP address,such as:

204.192.116.2

b Most computers also have a unique Internet name, which isalso referred to as an Internet address:

renoir.villanova.edu

kant.breakaway.com

b The first part indicates a particular computer (renoir)

b The rest is the domain name, indicating the organization(villanova.edu)

34

Domain Names

b The last section (the suffix) of each domain name usuallyindicates the type of organization:

educomorgnet

- educational institution- commercial business- non-profit organization- network-based organization

Sometimes the suffixindicates the country:

New suffix categoriesare being considered

ukaucase

- United Kingdom- Australia- Canada- Sweden

Page 20: Presentation slides for Java Software Solutionsmtrutsch/teaching/class/90301/HandoutAllSlides...Presentation slides for Java Software Solutions ... Presentation slides for Java Software

18

35

Domain Names

b A domain name can have several parts

b Unique domain names mean that multiple sites can haveindividual computers with the same local name

b When used, an Internet address is translated to an IPaddress by software called the Domain Name System (DNS)

b There is no one-to-one correspondence between the sectionsof an IP address and the sections of an Internet address

36

The World-Wide Web

b The World-Wide Web allows many different types ofinformation to be accessed using a common interface

b A browser is a program which accesses and presentsinformation• text, graphics, sound, audio, video, executable programs

b A Web document usually contains links to other Webdocuments, creating a hypermedia environment

b The term Web comes from the fact that information is notorganized in a linear fashion

Page 21: Presentation slides for Java Software Solutionsmtrutsch/teaching/class/90301/HandoutAllSlides...Presentation slides for Java Software Solutions ... Presentation slides for Java Software

19

37

The World-Wide Web

b Web documents are often defined using the HyperTextMarkup Language (HTML)

b Information on the Web is found using a Uniform ResourceLocator (URL):

http://www.lycos.com

http://www.villanova.edu/webinfo/domains.html

ftp://java.sun.com/applets/animation.zip

b A URL indicates a protocol (http), a domain, and possiblyspecific documents

38

Problem Solving

b The purpose of writing a program is to solve a problem

b The general steps in problem solving are:

• Understand the problem

• Dissect the problem into manageable pieces

• Design a solution

• Consider alternatives to the solution and refine it

• Implement the solution

• Test the solution and fix any problems that exist

Page 22: Presentation slides for Java Software Solutionsmtrutsch/teaching/class/90301/HandoutAllSlides...Presentation slides for Java Software Solutions ... Presentation slides for Java Software

20

39

Problem Solving

b Many software projects fail because the developer didn'treally understand the problem to be solved

b We must avoid assumptions and clarify ambiguities

b As problems and their solutions become larger, we mustorganize our development into manageable pieces

b This technique is fundamental to software development

b We will dissect our solutions into pieces called classes andobjects, taking an object-oriented approach

40

The Java Programming Language

b A programming language specifies the words and symbolsthat we can use to write a program

b A programming language employs a set of rules that dictatehow the words and symbols can be put together to formvalid program statements

b Java was created by Sun Microsystems, Inc.

b It was introduced in 1995 and has become quite popular

b It is an object-oriented language

Page 23: Presentation slides for Java Software Solutionsmtrutsch/teaching/class/90301/HandoutAllSlides...Presentation slides for Java Software Solutions ... Presentation slides for Java Software

21

41

Java Program Structure

b In the Java programming language:• A program is made up of one or more classes

• A class contains one or more methods

• A method contains program statements

b These terms will be explored in detail throughout thecourse

b A Java application always contains a method called main

b See Lincoln.java (page 26)

42

Java Program Structure

public class MyProgram

{

}

// comments about the class

class header

class body

Comments can be added almost anywhere

Page 24: Presentation slides for Java Software Solutionsmtrutsch/teaching/class/90301/HandoutAllSlides...Presentation slides for Java Software Solutions ... Presentation slides for Java Software

22

43

Java Program Structure

public class MyProgram

{

}

public static void main (String[] args)

{

}

// comments about the class

// comments about the method

method headermethod body

44

Comments

b Comments in a program are also called inlinedocumentation

b They should be included to explain the purpose of theprogram and describe processing steps

b They do not affect how a program works

b Java comments can take two forms:

// this comment runs to the end of the line

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

Page 25: Presentation slides for Java Software Solutionsmtrutsch/teaching/class/90301/HandoutAllSlides...Presentation slides for Java Software Solutions ... Presentation slides for Java Software

23

45

Identifiers

b Identifiers are the words a programmer uses in a program

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

b They cannot begin with a digit

b Java is case sensitive, therefore Total and total aredifferent identifiers

46

Identifiers

b Sometimes we choose identifiers ourselves when writing aprogram (such as Lincoln)

b Sometimes we are using another programmer's code, so weuse the identifiers that they chose (such as println)

b Often we use special identifiers called reserved words thatalready have a predefined meaning in the language

b A reserved word cannot be used in any other way

Page 26: Presentation slides for Java Software Solutionsmtrutsch/teaching/class/90301/HandoutAllSlides...Presentation slides for Java Software Solutions ... Presentation slides for Java Software

24

47

Reserved Words

b The Java reserved words:

abstractbooleanbreakbytebyvaluecasecastcatchcharclassconstcontinue

defaultdodoubleelseextendsfalsefinalfinallyfloatforfuturegeneric

gotoifimplementsimportinnerinstanceofintinterfacelongnativenewnull

operatorouterpackageprivateprotectedpublicrestreturnshortstaticsuperswitch

synchronizedthisthrowthrowstransienttruetryvarvoidvolatilewhile

48

White Space

b Spaces, blank lines, and tabs are collectively called whitespace

b White space is used to separate words and symbols in aprogram

b Extra white space is ignored

b A valid Java program can be formatted many differentways

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

b See Lincoln2.java and Lincoln3.java

Page 27: Presentation slides for Java Software Solutionsmtrutsch/teaching/class/90301/HandoutAllSlides...Presentation slides for Java Software Solutions ... Presentation slides for Java Software

25

49

Programming Language Levels

b There are four programming language levels:• machine language

• assembly language

• high-level language

• fourth-generation language

b Each type of CPU has its own specific machine language

b The other levels were created to make it easier for a humanbeing to write programs

50

Programming Languages

b A program must be translated into machine languagebefore it can be executed on a particular type of CPU

b This can be accomplished in several ways

b A compiler is a software tool which translates source codeinto a specific target language

b Often, that target language is the machine language for aparticular CPU type

b The Java approach is somewhat different

Page 28: Presentation slides for Java Software Solutionsmtrutsch/teaching/class/90301/HandoutAllSlides...Presentation slides for Java Software Solutions ... Presentation slides for Java Software

26

51

Java Translation and Execution

b The Java compiler translates Java source code into aspecial representation called bytecode

b Java bytecode is not the machine language for anytraditional CPU

b Another software tool, called an interpreter, translatesbytecode into machine language and executes it

b Therefore the Java compiler is not tied to any particularmachine

b Java is considered to be architecture-neutral

52

Java Translation and Execution

Java sourcecode

Machinecode

Javabytecode

Javainterpreter

Bytecodecompiler

Javacompiler

Page 29: Presentation slides for Java Software Solutionsmtrutsch/teaching/class/90301/HandoutAllSlides...Presentation slides for Java Software Solutions ... Presentation slides for Java Software

27

53

Development Environments

b There are many development environments which developJava software:• Sun Java Software Development Kit (SDK)

• Borland JBuilder

• MetroWork CodeWarrior

• Microsoft Visual J++

• Symantec Café

b Though the details of these environments differ, the basiccompilation and execution process is essentially the same

54

Syntax and Semantics

b The syntax rules of a language define how we can putsymbols, reserved words, and identifiers together to make avalid program

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

b A program that is syntactically correct is not necessarilylogically (semantically) correct

b A program will always do what we tell it to do, not what wemeant to tell it to do

Page 30: Presentation slides for Java Software Solutionsmtrutsch/teaching/class/90301/HandoutAllSlides...Presentation slides for Java Software Solutions ... Presentation slides for Java Software

28

55

Errors

b A program can have three types of errors

b The compiler will find problems with syntax and otherbasic issues (compile-time errors)• If compile-time errors exist, an executable version of the program is

not created

b A problem can occur during program execution, such astrying to divide by zero, which causes a program toterminate abnormally (run-time errors)

b A program may run, but produce incorrect results (logicalerrors)

56

Introduction to Graphics

b The last one or two sections of each chapter of the textbookfocus on graphical issues

b Most computer programs have graphical components

b A picture or drawing must be digitized for storage on acomputer

b A picture is broken down into pixels, and each pixel isstored separately

Page 31: Presentation slides for Java Software Solutionsmtrutsch/teaching/class/90301/HandoutAllSlides...Presentation slides for Java Software Solutions ... Presentation slides for Java Software

29

57

Representing Color

b A black and white picture can be stored using one bit perpixel (0 = white and 1 = black)

b A color picture requires more information, and there areseveral techniques for representing a particular color

b For example, every color can be represented as a mixture ofthe three primary colors Red, Green, and Blue

b In Java, each color is represented by three numbersbetween 0 and 255 that are collectively called an RGB value

58

Coordinate Systems

b Each pixel can be identified using a two-dimensionalcoordinate system

b When referring to a pixel in a Java program, we use acoordinate system with the origin in the upper left corner

Y

X(0, 0)

(112, 40)

112

40

Page 32: Presentation slides for Java Software Solutionsmtrutsch/teaching/class/90301/HandoutAllSlides...Presentation slides for Java Software Solutions ... Presentation slides for Java Software
Page 33: Presentation slides for Java Software Solutionsmtrutsch/teaching/class/90301/HandoutAllSlides...Presentation slides for Java Software Solutions ... Presentation slides for Java Software

1

Chapter 2: Objects and Primitive Data

Presentation slides for

Java Software SolutionsFoundations of Program Design

Second Edition

by John Lewis and William Loftus

Java Software Solutions is published by Addison-Wesley

Presentation slides are copyright 2000 by John Lewis and William Loftus. All rights reserved.Instructors using the textbook may use and modify these slides for pedagogical purposes.

2

Objects and Primitive Data

b We can now explore some more fundamental programmingconcepts

b Chapter 2 focuses on:• predefined objects

• primitive data

• the declaration and use of variables

• expressions and operator precedence

• class libraries

• Java applets

• drawing shapes

Page 34: Presentation slides for Java Software Solutionsmtrutsch/teaching/class/90301/HandoutAllSlides...Presentation slides for Java Software Solutions ... Presentation slides for Java Software

2

3

Introduction to Objects

b Initially, we can think of an object as a collection of servicesthat we can tell it to perform for us

b The services are defined by methods in a class that definesthe object

b In the Lincoln program, we invoked the println methodof the System.out object:

System.out.println ("Whatever you are, be a good one.");

object methodInformation provided to the method

(parameters)

4

The println and print Methods

b The System.out object provides another service as well

b The print method is similar to the println method,except that it does not advance to the next line

b Therefore anything printed after a print statement willappear on the same line

b See Countdown.java (page 53)

Page 35: Presentation slides for Java Software Solutionsmtrutsch/teaching/class/90301/HandoutAllSlides...Presentation slides for Java Software Solutions ... Presentation slides for Java Software

3

5

Abstraction

b An abstraction hides (or ignores) the right details at theright time

b An object is abstract in that we don't really have to thinkabout its internal details in order to use it

b We don't have to know how the println method works inorder to invoke it

b A human being can only manage seven (plus or minus 2)pieces of information at one time

b But if we group information into chunks (such as objects)we can manage many complicated pieces at once

b Therefore, we can write complex software by organizing itcarefully into classes and objects

6

The String Class

b Every character string is an object in Java, defined by theString class

b Every string literal, delimited by double quotation marks,represents a String object

b The string concatenation operator (+) is used to append onestring to the end of another

b It can also be used to append a number to a string

b A string literal cannot be broken across two lines in aprogram

b See Facts.java (page 56)

Page 36: Presentation slides for Java Software Solutionsmtrutsch/teaching/class/90301/HandoutAllSlides...Presentation slides for Java Software Solutions ... Presentation slides for Java Software

4

7

String Concatenation

b The plus operator (+) is also used for arithmetic addition

b The function that the + operator performs depends on thetype of the information on which it operates

b If both operands are strings, or if one is a string and one isa number, it performs string concatenation

b If both operands are numeric, it adds them

b The + operator is evaluated left to right

b Parentheses can be used to force the operation order

b See Addition.java (page 58)

8

Escape Sequences

b What if we wanted to print a double quote character?

b The following line would confuse the compiler because itwould interpret the second quote as the end of the string

System.out.println ("I said "Hello" to you.");

b An escape sequence is a series of characters that representsa special character

b An escape sequence begins with a backslash character (\),which indicates that the character(s) that follow should betreated in a special way

System.out.println ("I said \"Hello\" to you.");

Page 37: Presentation slides for Java Software Solutionsmtrutsch/teaching/class/90301/HandoutAllSlides...Presentation slides for Java Software Solutions ... Presentation slides for Java Software

5

9

Escape Sequences

b Some Java escape sequences:

b See Roses.java (page 59)

Escape Sequence

\b\t\n\r\"\'\\

Meaning

backspacetab

newlinecarriage returndouble quotesingle quotebackslash

10

Variables

b A variable is a name for a location in memory

b A variable must be declared, specifying the variable's nameand the type of information that will be held in it

int total;

int count, temp, result;

Multiple variables can be created in one declaration

data type variable name

Page 38: Presentation slides for Java Software Solutionsmtrutsch/teaching/class/90301/HandoutAllSlides...Presentation slides for Java Software Solutions ... Presentation slides for Java Software

6

Variables

b A variable can be given an initial value in the declaration

b When a variable is referenced in a program, its currentvalue is used

b See PianoKeys.java (page 60)

int sum = 0;int base = 32, max = 149;

12

Assignment

b An assignment statement changes the value of a variableb The assignment operator is the = sign

total = 55;

b You can only assign a value to a variable that is consistentwith the variable's declared type

b The expression on the right is evaluated and the result isstored in the variable on the left

b The value that was in total is overwritten

b See Geometry.java (page 62)

Page 39: Presentation slides for Java Software Solutionsmtrutsch/teaching/class/90301/HandoutAllSlides...Presentation slides for Java Software Solutions ... Presentation slides for Java Software

7

Constants

b A constant is an identifier that is similar to a variableexcept that it holds one value for its entire existence

b The compiler will issue an error if you try to change aconstant

b In Java, we use the final modifier to declare a constant

final int MIN_HEIGHT = 69;

b Constants:• give names to otherwise unclear literal values

• facilitate changes to the code

• prevent inadvertent errors

Primitive Data

b There are exactly eight primitive data types in Java

b Four of them represent integers:• byte, short, int, long

b Two of them represent floating point numbers:• float, double

b One of them represents characters:• char

b And one of them represents boolean values:• boolean

Page 40: Presentation slides for Java Software Solutionsmtrutsch/teaching/class/90301/HandoutAllSlides...Presentation slides for Java Software Solutions ... Presentation slides for Java Software

8

Numeric Primitive Data

b The difference between the various numeric primitive typesis their size, and therefore the values they can store:

Type

byteshortintlong

floatdouble

Storage

8 bits16 bits32 bits64 bits

32 bits64 bits

Min Value

-128-32,768-2,147,483,648< -9 x 1018

+/- 3.4 x 1038 with 7 significant digits+/- 1.7 x 10308 with 15 significant digits

Max Value

12732,7672,147,483,647> 9 x 1018

16

Characters

b A char variable stores a single character from theUnicode character set

b A character set is an ordered list of characters, and eachcharacter corresponds to a unique number

b The Unicode character set uses sixteen bits per character,allowing for 65,536 unique characters

b It is an international character set, containing symbols andcharacters from many world languages

b Character literals are delimited by single quotes:

'a' 'X' '7' '$' ',' '\n'

Page 41: Presentation slides for Java Software Solutionsmtrutsch/teaching/class/90301/HandoutAllSlides...Presentation slides for Java Software Solutions ... Presentation slides for Java Software

9

17

Characters

b The ASCII character set is older and smaller than Unicode,but is still quite popular

b The ASCII characters are a subset of the Unicodecharacter set, including:

uppercase letterslowercase letterspunctuationdigitsspecial symbolscontrol characters

A, B, C, …a, b, c, …period, semi-colon, …0, 1, 2, …&, |, \, …carriage return, tab, ...

18

Boolean

b A boolean value represents a true or false condition

b A boolean can also be used to represent any two states, suchas a light bulb being on or off

b The reserved words true and false are the only validvalues for a boolean type

boolean done = false;

Page 42: Presentation slides for Java Software Solutionsmtrutsch/teaching/class/90301/HandoutAllSlides...Presentation slides for Java Software Solutions ... Presentation slides for Java Software

10

Arithmetic Expressions

b An expression is a combination of operators and operands

b Arithmetic expressions compute numeric results and makeuse of the arithmetic operators:

Addition +Subtraction -Multiplication *Division /Remainder %

b If either or both operands to an arithmetic operator arefloating point, the result is a floating point

Division and Remainder

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

b The remainder operator (%) returns the remainder afterdividing the second operand into the first

14 / 3 equals?

8 / 12 equals?

4

0

14 % 3 equals?

8 % 12 equals?

2

8

Page 43: Presentation slides for Java Software Solutionsmtrutsch/teaching/class/90301/HandoutAllSlides...Presentation slides for Java Software Solutions ... Presentation slides for Java Software

11

Operator Precedence

b Operators can be combined into complex expressions

result = total + count / max - offset;

b Operators have a well-defined precedence whichdetermines the order in which they are evaluated

b Multiplication, division, and remainder are evaluated priorto addition, subtraction, and string concatenation

b Arithmetic operators with the same precedence areevaluated from left to right

b Parentheses can always be used to force the evaluationorder

Operator Precedence

b What is the order of evaluation in the followingexpressions?

a + b + c + d + e

1 432a + b * c - d / e

3 241

a / (b + c) - d % e

2 341

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

4 123

Page 44: Presentation slides for Java Software Solutionsmtrutsch/teaching/class/90301/HandoutAllSlides...Presentation slides for Java Software Solutions ... Presentation slides for Java Software

12

Assignment Revisited

b The assignment operator has a lower precedence than thearithmetic 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

Assignment Revisited

b The right and left hand sides of an assignment statementcan 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 45: Presentation slides for Java Software Solutionsmtrutsch/teaching/class/90301/HandoutAllSlides...Presentation slides for Java Software Solutions ... Presentation slides for Java Software

13

Data Conversions

b Sometimes it is convenient to convert data from one type toanother

b For example, we may want to treat an integer as a floatingpoint value during a computation

b Conversions must be handled carefully to avoid losinginformation

b Widening conversions are safest because they tend to gofrom a small data type to a larger one (such as a short toan int)

b Narrowing conversions can lose information because theytend to go from a large data type to a smaller one (such asan int to a short)

Data Conversions

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

• arithmetic promotion

• casting

b Assignment conversion occurs when a value of one type isassigned to a variable of another

b Only widening conversions can happen via assignment

b Arithmetic promotion happens automatically whenoperators in expressions convert their operands

Page 46: Presentation slides for Java Software Solutionsmtrutsch/teaching/class/90301/HandoutAllSlides...Presentation slides for Java Software Solutions ... Presentation slides for Java Software

14

Data Conversions

b Casting is the most powerful, and dangerous, technique forconversion

b Both widening and narrowing conversions can beaccomplished by explicitly casting a value

b To cast, the type is put in parentheses in front of the valuebeing converted

b For example, if total and count are integers, but wewant a floating point result when dividing them, we cancast total:

result = (float) total / count;

Creating Objects

b A variable either holds a primitive type, or it holds areference to an object

b A class name can be used as a type to declare an objectreference variable

String title;

b No object has been created with this declaration

b An object reference variable holds the address of an object

b The object itself must be created separately

Page 47: Presentation slides for Java Software Solutionsmtrutsch/teaching/class/90301/HandoutAllSlides...Presentation slides for Java Software Solutions ... Presentation slides for Java Software

15

Creating Objects

b We use the new operator to create an object

title = new String ("Java Software Solutions");

This calls the String constructor, which isa special method that sets up the object

b Creating an object is called instantiation

b An object is an instance of a particular class

Creating Objects

b Because strings are so common, we don't have to use thenew operator to create a String object

title = "Java Software Solutions";

b This is special syntax that only works for strings

b Once an object has been instantiated, we can use the dotoperator to invoke its methods

title.length()

Page 48: Presentation slides for Java Software Solutionsmtrutsch/teaching/class/90301/HandoutAllSlides...Presentation slides for Java Software Solutions ... Presentation slides for Java Software

16

String Methods

b The String class has several methods that are useful formanipulating strings

b Many of the methods return a value, such as an integer or anew String object

b See the list of String methods on page 75 and in AppendixM

b See StringMutation.java (page 77)

Class Libraries

b A class library is a collection of classes that we can use whendeveloping programs

b There is a Java standard class library that is part of anyJava development environment

b These classes are not part of the Java language per se, butwe rely on them heavily

b The System class and the String class are part of theJava standard class library

b Other class libraries can be obtained through third partyvendors, or you can create them yourself

Page 49: Presentation slides for Java Software Solutionsmtrutsch/teaching/class/90301/HandoutAllSlides...Presentation slides for Java Software Solutions ... Presentation slides for Java Software

17

Packages

b The classes of the Java standard class library are organizedinto packages

b Some of the packages in the standard class library are:

Package

java.langjava.appletjava.awtjavax.swingjava.netjava.util

Purpose

General supportCreating applets for the webGraphics and graphical user interfacesAdditional graphics capabilities and componentsNetwork communicationUtilities

The import Declaration

b When you want to use a class from a package, you coulduse its fully qualified name

java.util.Random

b Or you can import the class, then just use the class name

import java.util.Random;

b To import all classes in a particular package, you can usethe * wildcard character

import java.util.*;

Page 50: Presentation slides for Java Software Solutionsmtrutsch/teaching/class/90301/HandoutAllSlides...Presentation slides for Java Software Solutions ... Presentation slides for Java Software

18

The import Declaration

b All classes of the java.lang package are automaticallyimported into all programs

b That's why we didn't have to explicitly import the Systemor String classes in earlier programs

b The Random class is part of the java.util package

b It provides methods that generate pseudo-random numbers

b We often have to scale and shift a number into anappropriate range for a particular purpose

b See RandomNumbers.java (page 82)

Class Methods

b Some methods can be invoked through the class name,instead of through an object of the class

b These methods are called class methods or static methods

b The Math class contains many static methods, providingvarious mathematical functions, such as absolute value,trigonometry functions, square root, etc.

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

Page 51: Presentation slides for Java Software Solutionsmtrutsch/teaching/class/90301/HandoutAllSlides...Presentation slides for Java Software Solutions ... Presentation slides for Java Software

19

The Keyboard Class

b The Keyboard class is NOT part of the Java standardclass library

b It is provided by the authors of the textbook to makereading input from the keyboard easy

b Details of the Keyboard class are explored in Chapter 8

b For now we will simply make use of itb The Keyboard class is part of a package called cs1, and

contains several static methods for reading particular typesof data

b See Echo.java (page 86)

b See Quadratic.java (page 87)

Formatting Output

b The NumberFormat class has static methods that return aformatter object

getCurrencyInstance()

getPercentInstance()

b Each formatter object has a method called format thatreturns a string with the specified information in theappropriate format

b See Price.java (page 89)

Page 52: Presentation slides for Java Software Solutionsmtrutsch/teaching/class/90301/HandoutAllSlides...Presentation slides for Java Software Solutions ... Presentation slides for Java Software

20

Formatting Output

b The DecimalFormat class can be used to format afloating point value in generic ways

b For example, you can specify that the number be printed tothree decimal places

b The constructor of the DecimalFormat class takes astring that represents a pattern for the formatted number

b See CircleStats.java (page 91)

Applets

b A Java application is a stand-alone program with a mainmethod (like the ones we've seen so far)

b An applet is a Java program that is intended to transportedover the web and executed using a web browser

b An applet can also be executed using the appletviewer toolof the Java Software Development Kit

b An applet doesn't have a main method

b Instead, there are several special methods that servespecific purposes

b The paint method, for instance, is automatically executedand is used to draw the applets contents

Page 53: Presentation slides for Java Software Solutionsmtrutsch/teaching/class/90301/HandoutAllSlides...Presentation slides for Java Software Solutions ... Presentation slides for Java Software

21

Applets

b The paint method accepts a parameter that is an object ofthe Graphics class

b A Graphics object defines a graphics context on which wecan draw shapes and text

b The Graphics class has several methods for drawingshapes

b The class that defines the applet extends the Applet class

b This makes use of inheritance, an object-oriented conceptexplored in more detail in Chapter 7

b See Einstein.java (page 93)

Applets

b An applet is embedded into an HTML file using a tag thatreferences the bytecode file of the applet class

b It is actually the bytecode version of the program that istransported across the web

b The applet is executed by a Java interpreter that is part ofthe browser

Page 54: Presentation slides for Java Software Solutionsmtrutsch/teaching/class/90301/HandoutAllSlides...Presentation slides for Java Software Solutions ... Presentation slides for Java Software

22

Drawing Shapes

b Let's explore some of the methods of the Graphics classthat draw shapes in more detail

b A shape can be filled or unfilled, depending on whichmethod is invoked

b The method parameters specify coordinates and sizes

b Recall from Chapter 1 that the Java coordinate system hasthe origin in the upper left corner

b Many shapes with curves, like an oval, are drawn byspecifying its bounding rectangle

b An arc can be thought of as a section of an oval

Drawing a Line

X

Y

10

20

150

45

page.drawLine (10, 20, 150, 45);

page.drawLine (150, 45, 10, 20);

or

Page 55: Presentation slides for Java Software Solutionsmtrutsch/teaching/class/90301/HandoutAllSlides...Presentation slides for Java Software Solutions ... Presentation slides for Java Software

23

Drawing a Rectangle

X

Y

page.drawRect (50, 20, 100, 40);

50

20

100

40

Drawing an Oval

X

Y

page.drawOval (175, 20, 50, 80);

175

20

50

80

boundingrectangle

Page 56: Presentation slides for Java Software Solutionsmtrutsch/teaching/class/90301/HandoutAllSlides...Presentation slides for Java Software Solutions ... Presentation slides for Java Software

24

The Color Class

b A color is defined in a Java program using an objectcreated from the Color class

b The Color class also contains several static predefinedcolors

b Every graphics context has a current foreground color

b Every drawing surface has a background color

b See Snowman.java (page 99-100)

Page 57: Presentation slides for Java Software Solutionsmtrutsch/teaching/class/90301/HandoutAllSlides...Presentation slides for Java Software Solutions ... Presentation slides for Java Software

1

Chapter 3: Program Statements

Presentation slides for

Java Software SolutionsFoundations of Program Design

Second Edition

by John Lewis and William Loftus

Java Software Solutions is published by Addison-Wesley

Presentation slides are copyright 2000 by John Lewis and William Loftus. All rights reserved.Instructors using the textbook may use and modify these slides for pedagogical purposes.

2

Program Statements

b We will now examine some other program statements

b Chapter 3 focuses on:• the flow of control through a method

• decision-making statements

• operators for making complex decisions

• repetition statements

• software development stages

• more drawing techniques

Page 58: Presentation slides for Java Software Solutionsmtrutsch/teaching/class/90301/HandoutAllSlides...Presentation slides for Java Software Solutions ... Presentation slides for Java Software

2

Flow of Control

b Unless indicated otherwise, the order of statementexecution through a method is linear: one after the other inthe order they are written

b Some programming statements modify that order, allowingus to:• decide whether or not to execute a particular statement, or

• perform a statement over and over repetitively

b The order of statement execution is called the flow ofcontrol

Conditional Statements

b A conditional statement lets us choose which statement willbe executed next

b Therefore they are sometimes called selection statements

b Conditional statements give us the power to make basicdecisions

b Java's conditional statements are the if statement, the if-elsestatement, and the switch statement

Page 59: Presentation slides for Java Software Solutionsmtrutsch/teaching/class/90301/HandoutAllSlides...Presentation slides for Java Software Solutions ... Presentation slides for Java Software

3

5

The if Statement

b The if statement has the following syntax:

if ( condition ) statement;

if is a Javareserved word

The condition must be a boolean expression.It must evaluate to either true or false.

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

The if Statement

b An example of an if statement:

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

First, the condition is evaluated. The value of sumis either greater than the value of MAX, or it is not.

If the condition is true, the assignment statement is executed.If it is not, the assignment statement is skipped.

Either way, the call to println is executed next.

b See Age.java (page 112)

Page 60: Presentation slides for Java Software Solutionsmtrutsch/teaching/class/90301/HandoutAllSlides...Presentation slides for Java Software Solutions ... Presentation slides for Java Software

4

Logic of an if statement

conditionevaluated

false

statement

true

8

Boolean Expressions

b A condition often uses one of Java's equality operators orrelational operators, which all return boolean results:

== equal to

!= not equal to

< less than

> greater than

<= less than or equal to

>= greater than or equal to

b Note the difference between the equality operator (==) andthe assignment operator (=)

Page 61: Presentation slides for Java Software Solutionsmtrutsch/teaching/class/90301/HandoutAllSlides...Presentation slides for Java Software Solutions ... Presentation slides for Java Software

5

9

The if-else Statement

b An else clause can be added to an if statement to make it anif-else statement:

if ( condition ) statement1;else statement2;

b See Wages.java (page 116)

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

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

Logic of an if-else statement

conditionevaluated

statement1

true false

statement2

Page 62: Presentation slides for Java Software Solutionsmtrutsch/teaching/class/90301/HandoutAllSlides...Presentation slides for Java Software Solutions ... Presentation slides for Java Software

6

11

Block Statements

b Several statements can be grouped together into a blockstatement

b A block is delimited by braces ( { … } )

b A block statement can be used wherever a statement iscalled for in the Java syntax

b For example, in an if-else statement, the if portion, or theelse portion, or both, could be block statements

b See Guessing.java (page 117)

12

Nested if Statements

b The statement executed as a result of an if statement or elseclause could be another if statement

b These are called nested if statements

b See MinOfThree.java (page 118)

b An else clause is matched to the last unmatched if (nomatter what the indentation implies)

Page 63: Presentation slides for Java Software Solutionsmtrutsch/teaching/class/90301/HandoutAllSlides...Presentation slides for Java Software Solutions ... Presentation slides for Java Software

7

Comparing Characters

b We can use the relational operators on character data

b The results are based on the Unicode character set

b The following condition is true because the character '+'comes before the character 'J' in Unicode:

if ('+' < 'J') System.out.println ("+ is less than J");

b The uppercase alphabet (A-Z) and the lowercase alphabet(a-z) both appear in alphabetical order in Unicode

Comparing Strings

b Remember that a character string in Java is an object

b We cannot use the relational operators to compare strings

b The equals method can be called on a string to determineif two strings contain exactly the same characters in thesame order

b The String class also contains a method called compareToto determine if one string comes before anotheralphabetically (as determined by the Unicode character set)

Page 64: Presentation slides for Java Software Solutionsmtrutsch/teaching/class/90301/HandoutAllSlides...Presentation slides for Java Software Solutions ... Presentation slides for Java Software

8

Comparing Floating Point Values

b We also have to be careful when comparing two floatingpoint values (float or double) for equality

b You should rarely use the equality operator (==) whencomparing two floats

b In many situations, you might consider two floating pointnumbers to be "close enough" even if they aren't exactlyequal

b Therefore, to determine the equality of two floats, you maywant to use the following technique:

if (Math.abs (f1 - f2) < 0.00001) System.out.println ("Essentially equal.");

16

The switch Statement

b The switch statement provides another means to decidewhich statement to execute next

b The switch statement evaluates an expression, thenattempts to match the result to one of several possible cases

b Each case contains a value and a list of statements

b The flow of control transfers to statement list associatedwith the first value that matches

Page 65: Presentation slides for Java Software Solutionsmtrutsch/teaching/class/90301/HandoutAllSlides...Presentation slides for Java Software Solutions ... Presentation slides for Java Software

9

The switch Statement

b The general syntax of a switch statement is:

switch ( expression ){ case value1 : statement-list1 case value2 : statement-list2 case value3 : statement-list3 case ...

}

switchandcase

arereserved

words

If expressionmatches value2,control jumpsto here

The switch Statement

b Often a break statement is used as the last statement in eachcase's statement list

b A break statement causes control to transfer to the end ofthe switch statement

b If a break statement is not used, the flow of control willcontinue into the next case

b Sometimes this can be helpful, but usually we only want toexecute the statements associated with one case

Page 66: Presentation slides for Java Software Solutionsmtrutsch/teaching/class/90301/HandoutAllSlides...Presentation slides for Java Software Solutions ... Presentation slides for Java Software

10

The switch Statement

b A switch statement can have an optional default case

b The default case has no associated value and simply usesthe reserved word default

b If the default case is present, control will transfer to it if noother case value matches

b Though the default case can be positioned anywhere in theswitch, it is usually placed at the end

b If there is no default case, and no other value matches,control falls through to the statement after the switch

The switch Statement

b The expression of a switch statement must result in anintegral data type, like an integer or character; it cannot bea floating point value

b Note that the implicit boolean condition in a switchstatement is equality - it tries to match the expression witha value

b You cannot perform relational checks with a switchstatement

b See GradeReport.java (page 121)

Page 67: Presentation slides for Java Software Solutionsmtrutsch/teaching/class/90301/HandoutAllSlides...Presentation slides for Java Software Solutions ... Presentation slides for Java Software

11

21

Logical Operators

b Boolean expressions can also use the following logicaloperators:

! Logical NOT

&& Logical AND

|| Logical OR

b They all take boolean operands and produce booleanresults

b Logical NOT is a unary operator (it has one operand), butlogical AND and logical OR are binary operators (they eachhave two operands)

22

Logical NOT

b The logical NOT operation is also called logical negation orlogical complement

b If some boolean condition a is true, then !a is false; if a isfalse, then !a is true

b Logical expressions can be shown using truth tables

a

truefalse

!a

falsetrue

Page 68: Presentation slides for Java Software Solutionsmtrutsch/teaching/class/90301/HandoutAllSlides...Presentation slides for Java Software Solutions ... Presentation slides for Java Software

12

23

Logical AND and Logical OR

b The logical and expression

a && b

is true if both a and b are true, and false otherwise

b The logical or expression

a || b

is true if a or b or both are true, and false otherwise

Truth Tables

b A truth table shows the possible true/false combinations ofthe terms

b Since && and || each have two operands, there are fourpossible combinations of true and false

a

truetruefalsefalse

b

truefalsetruefalse

a && b

truefalsefalsefalse

a || b

truetruetruefalse

Page 69: Presentation slides for Java Software Solutionsmtrutsch/teaching/class/90301/HandoutAllSlides...Presentation slides for Java Software Solutions ... Presentation slides for Java Software

13

25

Logical Operators

b Conditions in selection statements and loops can use logicaloperators to form complex expressions

if (total < MAX && !found) System.out.println ("Processing…");

b Logical operators have precedence relationships betweenthemselves and other operators

26

Truth Tables

b Specific expressions can be evaluated using truth tables

total < MAX

falsefalsetruetrue

found

falsetruefalsetrue

!found

truefalsetruefalse

total < MAX && !found

falsefalsetruefalse

Page 70: Presentation slides for Java Software Solutionsmtrutsch/teaching/class/90301/HandoutAllSlides...Presentation slides for Java Software Solutions ... Presentation slides for Java Software

14

27

More Operators

b To round out our knowledge of Java operators, let'sexamine a few more

b In particular, we will examine the:

• increment and decrement operators

• assignment operators

• conditional operator

28

Increment and Decrement Operators

b The increment and decrement operators are arithmetic andoperate on one operand

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

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

b The statement

count++;

is essentially equivalent to

count = count + 1;

Page 71: Presentation slides for Java Software Solutionsmtrutsch/teaching/class/90301/HandoutAllSlides...Presentation slides for Java Software Solutions ... Presentation slides for Java Software

15

29

Increment and Decrement Operators

b The increment and decrement operators can be applied inprefix form (before the variable) or postfix form (after thevariable)

b When used alone in a statement, the prefix and postfixforms are basically equivalent. That is,

count++;

is equivalent to

++count;

30

Increment and Decrement Operators

b When used in a larger expression, the prefix and postfixforms have a different effect

b In both cases the variable is incremented (decremented)

b But the value used in the larger expression depends on theform:

Expression

count++++countcount----count

Operation

add 1add 1

subtract 1subtract 1

Value of Expression

old valuenew valueold valuenew value

Page 72: Presentation slides for Java Software Solutionsmtrutsch/teaching/class/90301/HandoutAllSlides...Presentation slides for Java Software Solutions ... Presentation slides for Java Software

16

31

Increment and Decrement Operators

b If count currently contains 45, then

total = count++;

assigns 45 to total and 46 to count

b If count currently contains 45, then

total = ++count;

assigns the value 46 to both total and count

32

Assignment Operators

b Often we perform an operation on a variable, then store theresult back into that variable

b Java provides assignment operators to simplify that process

b For example, the statement

num += count;

is equivalent to

num = num + count;

Page 73: Presentation slides for Java Software Solutionsmtrutsch/teaching/class/90301/HandoutAllSlides...Presentation slides for Java Software Solutions ... Presentation slides for Java Software

17

33

Assignment Operators

b There are many assignment operators, including thefollowing:

Operator

+=-=*=/=%=

Example

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

Equivalent To

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

34

Assignment Operators

b The right hand side of an assignment operator can be acomplete expression

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

b Therefore

result /= (total-MIN) % num;

is equivalent to

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

Page 74: Presentation slides for Java Software Solutionsmtrutsch/teaching/class/90301/HandoutAllSlides...Presentation slides for Java Software Solutions ... Presentation slides for Java Software

18

35

The Conditional Operator

b Java has a conditional operator that evaluates a booleancondition that determines which of two other expressions isevaluated

b The result of the chosen expression is the result of the entireconditional operator

b Its syntax is:

condition ? expression1 : expression2

b If the condition is true, expression1 is evaluated; if it isfalse, expression2 is evaluated

36

The Conditional Operator

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

b For example:

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

b If num1 is greater that num2, then num1 is assigned tolarger; otherwise, num2 is assigned to larger

b The conditional operator is ternary, meaning that itrequires three operands

Page 75: Presentation slides for Java Software Solutionsmtrutsch/teaching/class/90301/HandoutAllSlides...Presentation slides for Java Software Solutions ... Presentation slides for Java Software

19

37

The Conditional Operator

b Another example:

System.out.println ("Your change is " + count +

(count == 1) ? "Dime" : "Dimes");

b If count equals 1, then "Dime" is printed

b If count is anything other than 1, then "Dimes" isprinted

Repetition Statements

b Repetition statements allow us to execute a statementmultiple times repetitively

b They are often simply referred to as loops

b Like conditional statements, they are controlled by booleanexpressions

b Java has three kinds of repetition statements: the whileloop, the do loop, and the for loop

b The programmer must choose the right kind of loop for thesituation

Page 76: Presentation slides for Java Software Solutionsmtrutsch/teaching/class/90301/HandoutAllSlides...Presentation slides for Java Software Solutions ... Presentation slides for Java Software

20

39

The while Statement

b The while statement has the following syntax:

while ( condition ) statement;

while is areserved word

If the condition is true, the statement is executed.Then the condition is evaluated again.

The statement is executed repetitively untilthe condition becomes false.

Logic of a while loop

statement

true

conditionevaluated

false

Page 77: Presentation slides for Java Software Solutionsmtrutsch/teaching/class/90301/HandoutAllSlides...Presentation slides for Java Software Solutions ... Presentation slides for Java Software

21

41

The while Statement

b Note that if the condition of a while statement is falseinitially, the statement is never executed

b Therefore, the body of a while loop will execute zero ormore times

b See Counter.java (page 133)

b See Average.java (page 134)

b See WinPercentage.java (page 136)

42

Infinite Loops

b The body of a while loop must eventually make thecondition false

b If not, it is an infinite loop, which will execute until the userinterrupts the program

b See Forever.java (page 138)

b This is a common type of logical error

b You should always double check to ensure that your loopswill terminate normally

Page 78: Presentation slides for Java Software Solutionsmtrutsch/teaching/class/90301/HandoutAllSlides...Presentation slides for Java Software Solutions ... Presentation slides for Java Software

22

Nested Loops

b Similar to nested if statements, loops can be nested as well

b That is, the body of a loop could contain another loop

b Each time through the outer loop, the inner loop will gothrough its entire set of iterations

b See PalindromeTester.java (page 137)

The do Statement

b The do statement has the following syntax:

do{ statement;}while ( condition )

Uses boththe do andwhile

reservedwords

The statement is executed once initially, then the condition is evaluated

The statement is repetitively executed until the condition becomes false

Page 79: Presentation slides for Java Software Solutionsmtrutsch/teaching/class/90301/HandoutAllSlides...Presentation slides for Java Software Solutions ... Presentation slides for Java Software

23

Logic of a do loop

true

conditionevaluated

statement

false

The do Statement

b A do loop is similar to a while loop, except that thecondition is evaluated after the body of the loop is executed

b Therefore the body of a do loop will execute at least onetime

b See Counter2.java (page 143)

b See ReverseNumber.java (page 144)

Page 80: Presentation slides for Java Software Solutionsmtrutsch/teaching/class/90301/HandoutAllSlides...Presentation slides for Java Software Solutions ... Presentation slides for Java Software

24

Comparing the while and do loops

statement

true

conditionevaluated

false

while loop

true

conditionevaluated

statement

false

do loop

The for Statement

b The for statement has the following syntax:

for ( initialization ; condition ; increment ) statement;

Reservedword

The initialization portionis 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 81: Presentation slides for Java Software Solutionsmtrutsch/teaching/class/90301/HandoutAllSlides...Presentation slides for Java Software Solutions ... Presentation slides for Java Software

25

The for Statement

b A for loop is equivalent to the following while loopstructure:

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

Logic of a for loop

statement

true

conditionevaluated

false

increment

initialization

Page 82: Presentation slides for Java Software Solutionsmtrutsch/teaching/class/90301/HandoutAllSlides...Presentation slides for Java Software Solutions ... Presentation slides for Java Software

26

The for Statement

b Like a while loop, the condition of a for statement is testedprior to executing the loop body

b Therefore, the body of a for loop will execute zero or moretimes

b It is well suited for executing a specific number of timesthat can be determined in advance

b See Counter3.java (page 146)

b See Multiples.java (page 147)

b See Stars.java (page 150)

The for Statement

b Each expression in the header of a for loop 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, andtherefore creates an infinite loop

• If the increment is left out, no increment operation is performed

b Both semi-colons are always required in the for loop header

Page 83: Presentation slides for Java Software Solutionsmtrutsch/teaching/class/90301/HandoutAllSlides...Presentation slides for Java Software Solutions ... Presentation slides for Java Software

27

53

Program Development

b The creation of software involves four basic activities:

• establishing the requirements

• creating a design

• implementing the code

• testing the implementation

b The development process is much more involved than this,but these basic steps are a good starting point

54

Requirements

b Requirements specify the tasks a program must accomplish(what to do, not how to do it)

b They often include a description of the user interface

b An initial set of requirements are often provided, butusually must be critiqued, modified, and expanded

b It is often difficult to establish detailed, unambiguous,complete requirements

b Careful attention to the requirements can save significanttime and money in the overall project

Page 84: Presentation slides for Java Software Solutionsmtrutsch/teaching/class/90301/HandoutAllSlides...Presentation slides for Java Software Solutions ... Presentation slides for Java Software

28

55

Design

b An algorithm is a step-by-step process for solving a problem

b A program follows one or more algorithms to accomplishits goal

b The design of a program specifies the algorithms and dataneeded

b In object-oriented development, the design establishes theclasses, objects, and methods that are required

b The details of a method may be expressed in pseudocode,which is code-like, but does not necessarily follow anyspecific syntax

56

Implementation

b Implementation is the process of translating a design intosource code

b Most novice programmers think that writing code is theheart of software development, but it actually should be theleast creative step

b Almost all important decisions are made duringrequirements analysis and design

b Implementation should focus on coding details, includingstyle guidelines and documentation

b See ExamGrades.java (page 155)

Page 85: Presentation slides for Java Software Solutionsmtrutsch/teaching/class/90301/HandoutAllSlides...Presentation slides for Java Software Solutions ... Presentation slides for Java Software

29

57

Testing

b A program should be executed multiple times with variousinput in an attempt to find errors

b Debugging is the process of discovering the cause of aproblem and fixing it

b Programmers often erroneously think that there is "onlyone more bug" to fix

b Tests should focus on design details as well as overallrequirements

More Drawing Techniques

b Conditionals and loops can greatly enhance our ability tocontrol graphics

b See Bullseye.java (page 157)

b See Boxes.java (page 159)

b See BarHeights.java (page 162)

Page 86: Presentation slides for Java Software Solutionsmtrutsch/teaching/class/90301/HandoutAllSlides...Presentation slides for Java Software Solutions ... Presentation slides for Java Software
Page 87: Presentation slides for Java Software Solutionsmtrutsch/teaching/class/90301/HandoutAllSlides...Presentation slides for Java Software Solutions ... Presentation slides for Java Software

1

Chapter 4: Writing Classes

Presentation slides for

Java Software SolutionsFoundations of Program Design

Second Edition

by John Lewis and William Loftus

Java Software Solutions is published by Addison-Wesley

Presentation slides are copyright 2000 by John Lewis and William Loftus. All rights reserved.Instructors using the textbook may use and modify these slides for pedagogical purposes.

2

Writing Classes

b We've been using predefined classes. Now we will learn towrite our own classes to define new objects

b Chapter 4 focuses on:• class declarations

• method declarations

• instance variables

• encapsulation

• method overloading

• graphics-based objects

Page 88: Presentation slides for Java Software Solutionsmtrutsch/teaching/class/90301/HandoutAllSlides...Presentation slides for Java Software Solutions ... Presentation slides for Java Software

2

3

Objects

b An object has:• state - descriptive characteristics

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

b For example, consider a coin that can be flipped so that it'sface shows either "heads" or "tails"

b The state of the coin is its current face (heads or tails)

b The behavior of the coin is that it can be flipped

b Note that the behavior of the coin might change its state

4

Classes

b A class is a blueprint of an object

b It is the model or pattern from which objects are created

b For example, the String class is used to define Stringobjects

b Each String object contains specific characters (its state)

b Each String object can perform services (behaviors) suchas toUpperCase

Page 89: Presentation slides for Java Software Solutionsmtrutsch/teaching/class/90301/HandoutAllSlides...Presentation slides for Java Software Solutions ... Presentation slides for Java Software

3

Classes

b The String class was provided for us by the Javastandard class library

b But we can also write our own classes that define specificobjects that we need

b For example, suppose we wanted to write a program thatsimulates the flipping of a coin

b We could write a Coin class to represent a coin object

Classes

b A class contains data declarations and method declarations

int x, y;char ch;

Data declarations

Method declarations

Page 90: Presentation slides for Java Software Solutionsmtrutsch/teaching/class/90301/HandoutAllSlides...Presentation slides for Java Software Solutions ... Presentation slides for Java Software

4

Data Scope

b The scope of data is the area in a program in which thatdata can be used (referenced)

b Data declared at the class level can be used by all methodsin that class

b Data declared within a method can only be used in thatmethod

b Data declared within a method is called local data

Writing Methods

b A method declaration specifies the code that will be executedwhen the method is invoked (or called)

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

b When complete, the flow returns to the place where themethod was called and continues

b The invocation may or may not return a value, dependingon how the method was defined

Page 91: Presentation slides for Java Software Solutionsmtrutsch/teaching/class/90301/HandoutAllSlides...Presentation slides for Java Software Solutions ... Presentation slides for Java Software

5

myMethod();

myMethodcompute

Method Control Flow

b The called method could be within the same class, in whichcase only the method name is needed

doIt

helpMe

helpMe();

obj.doIt();

main

Method Control Flow

b The called method could be part of another class or object

Page 92: Presentation slides for Java Software Solutionsmtrutsch/teaching/class/90301/HandoutAllSlides...Presentation slides for Java Software Solutions ... Presentation slides for Java Software

6

The Coin Class

b In our Coin class we could define the following data:• face, an integer that represents the current face

• HEADS and TAILS, integer constants that represent the twopossible states

b We might also define the following methods:• a Coin constructor, to set up the object

• a flip method, to flip the coin

• a getFace method, to return the current face

• a toString method, to return a string description for printing

The Coin Class

b See CountFlips.java (page 179)

b See Coin.java (page 180)

b Once the Coin class has been defined, we can use it againin other programs as needed

b Note that the CountFlips program did not use thetoString method

b A program will not necessarily use every service providedby an object

Page 93: Presentation slides for Java Software Solutionsmtrutsch/teaching/class/90301/HandoutAllSlides...Presentation slides for Java Software Solutions ... Presentation slides for Java Software

7

Instance Data

b The face variable in the Coin class is called instance databecause each instance (object) of the Coin class has its own

b A class declares the type of the data, but it does not reserveany memory space for it

b Every time a Coin object is created, a new face variableis created as well

b The objects of a class share the method definitions, but theyhave unique data space

b That's the only way two objects can have different states

Instance Data

b See FlipRace.java (page 182)

face 0

coin1

int face;

class Coin

face 1

coin2

Page 94: Presentation slides for Java Software Solutionsmtrutsch/teaching/class/90301/HandoutAllSlides...Presentation slides for Java Software Solutions ... Presentation slides for Java Software

8

15

Encapsulation

b You can take one of two views of an object:• internal - the structure of its data, the algorithms used by its

methods

• external - the interaction of the object with other objects in theprogram

b From the external view, an object is an encapsulated entity,providing a set of specific services

b These services define the interface to the object

b Recall from Chapter 2 that an object is an abstraction,hiding details from the rest of the system

16

Encapsulation

b An object should be self-governing

b Any changes to the object's state (its variables) should beaccomplished by that object's methods

b We should make it difficult, if not impossible, for one objectto "reach in" and alter another object's state

b The user, or client, of an object can request its services, butit should not have to be aware of how those services areaccomplished

Page 95: Presentation slides for Java Software Solutionsmtrutsch/teaching/class/90301/HandoutAllSlides...Presentation slides for Java Software Solutions ... Presentation slides for Java Software

9

17

Encapsulation

b An encapsulated object can be thought of as a black box

b Its inner workings are hidden to the client, which onlyinvokes the interface methods

Client Methods

Data

18

Visibility Modifiers

b In Java, we accomplish encapsulation through theappropriate use of visibility modifiers

b A modifier is a Java reserved word that specifies particularcharacteristics of a method or data value

b We've used the modifier final to define a constant

b Java has three visibility modifiers: public, private,and protected

b We will discuss the protected modifier later

Page 96: Presentation slides for Java Software Solutionsmtrutsch/teaching/class/90301/HandoutAllSlides...Presentation slides for Java Software Solutions ... Presentation slides for Java Software

10

19

Visibility Modifiers

b Members of a class that are declared with public visibilitycan be accessed from anywhere

b Members of a class that are declared with private visibilitycan only be accessed from inside the class

b Members declared without a visibility modifier have defaultvisibility and can be accessed by any class in the samepackage

b Java modifiers are discussed in detail in Appendix F

20

Visibility Modifiers

b As a general rule, no object's data should be declared withpublic visibility

b Methods that provide the object's services are usuallydeclared with public visibility so that they can be invokedby clients

b Public methods are also called service methods

b A method created simply to assist a service method is calleda support method

b Since a support method is not intended to be called by aclient, it should not be declared with public visibility

Page 97: Presentation slides for Java Software Solutionsmtrutsch/teaching/class/90301/HandoutAllSlides...Presentation slides for Java Software Solutions ... Presentation slides for Java Software

11

Method Declarations Revisited

b 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 argument

Method Declarations

b 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 expression must beconsistent with the return type

sum and resultare local data

They are created eachtime the method is called,and are destroyed whenit finishes executing

Page 98: Presentation slides for Java Software Solutionsmtrutsch/teaching/class/90301/HandoutAllSlides...Presentation slides for Java Software Solutions ... Presentation slides for Java Software

12

23

The return Statement

b The return type of a method indicates the type of value thatthe method sends back to the calling location

b A method that does not return a value has a void returntype

b The return statement specifies the value that will bereturned

b Its expression must conform to the return type

Parameters

b Each time a method is called, the actual arguments in theinvocation are copied into the formal arguments

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 99: Presentation slides for Java Software Solutionsmtrutsch/teaching/class/90301/HandoutAllSlides...Presentation slides for Java Software Solutions ... Presentation slides for Java Software

13

25

Constructors Revisited

b Recall that a constructor is a special method that is used toset up a newly created object

b When writing a constructor, remember that:• it has the same name as the class

• it does not return a value• it has no return type, not even void

• it often sets the initial values of instance variables

b The programmer does not have to define a constructor fora class

Writing Classes

b See BankAccounts.java (page 188)

b See Account.java (page 189)

b An aggregate object is an object that contains references toother objects

b An Account object is an aggregate object because itcontains a reference to a String object (that holds theowner's name)

b An aggregate object represents a has-a relationship

b A bank account has a name

Page 100: Presentation slides for Java Software Solutionsmtrutsch/teaching/class/90301/HandoutAllSlides...Presentation slides for Java Software Solutions ... Presentation slides for Java Software

14

Writing Classes

b Sometimes an object has to interact with other objects ofthe same type

b For example, we might add two Rational number objectstogether as follows:

r3 = r1.add(r2);

b One object (r1) is executing the method and another (r2) ispassed as a parameter

b See RationalNumbers.java (page 196)

b See Rational.java (page 197)

28

Overloading Methods

b Method overloading is the process of using the same methodname for multiple methods

b The signature of each overloaded method must be unique

b The signature includes the number, type, and order of theparameters

b The compiler must be able to determine which version ofthe method is being invoked by analyzing the parameters

b The return type of the method is not part of the signature

Page 101: Presentation slides for Java Software Solutionsmtrutsch/teaching/class/90301/HandoutAllSlides...Presentation slides for Java Software Solutions ... Presentation slides for Java Software

15

Overloading Methods

float tryMe (int x){ return x + .375;}

Version 1

float tryMe (int x, float y){ return x*y;}

Version 2

result = tryMe (25, 4.32)

Invocation

30

Overloaded Methods

b The println method is overloaded:

println (String s)

println (int i)

println (double d)

etc.

b The following lines invoke different versions of theprintln method:

System.out.println ("The total is:");

System.out.println (total);

Page 102: Presentation slides for Java Software Solutionsmtrutsch/teaching/class/90301/HandoutAllSlides...Presentation slides for Java Software Solutions ... Presentation slides for Java Software

16

31

Overloading Methods

b Constructors can be overloaded

b An overloaded constructor provides multiple ways to set upa new object

b See SnakeEyes.java (page 203)

b See Die.java (page 204)

The StringTokenizer Class

b The next example makes use of the StringTokenizerclass, which is defined in the java.util package

b A StringTokenizer object separates a string intosmaller substrings (tokens)

b By default, the tokenizer separates the string at white space

b The StringTokenizer constructor takes the originalstring to be separated as a parameter

b Each call to the nextToken method returns the next tokenin the string

Page 103: Presentation slides for Java Software Solutionsmtrutsch/teaching/class/90301/HandoutAllSlides...Presentation slides for Java Software Solutions ... Presentation slides for Java Software

17

Method Decomposition

b A method should be relatively small, so that it can bereadily understood as a single entity

b A potentially large method should be decomposed intoseveral smaller methods as needed for clarity

b Therefore, a service method of an object may call one ormore support methods to accomplish its goal

b See PigLatin.java (page 207)

b See PigLatinTranslator.java (page 208)

Applet Methods

b In previous examples we've used the paint method of theApplet class to draw on an applet

b The Applet class has several methods that are invokedautomatically at certain points in an applet's life

b The init method, for instance, is executed only once whenthe applet is initially loaded

b The Applet class also contains other methods thatgenerally assist in applet processing

Page 104: Presentation slides for Java Software Solutionsmtrutsch/teaching/class/90301/HandoutAllSlides...Presentation slides for Java Software Solutions ... Presentation slides for Java Software

18

Graphical Objects

b Any object we define by writing a class can have graphicalelements

b The object must simply obtain a graphics context (aGraphics object) in which to draw

b An applet can pass its graphics context to another objectjust as it can any other parameter

b See LineUp.java (page 212)

b See StickFigure.java (page 215)

Page 105: Presentation slides for Java Software Solutionsmtrutsch/teaching/class/90301/HandoutAllSlides...Presentation slides for Java Software Solutions ... Presentation slides for Java Software

PPrreesseennttaattiioonn sslliiddeess ffoorr

JJaavvaa SSooffttwwaarree SSoolluuttiioonnssFFoouunnddaattiioonnss ooff PPrrooggrraamm DDeessiiggnn

SSeeccoonndd EEddiittiioonn

bbyy JJoohhnn LLeewwiiss aanndd WWiilllliiaamm LLooffttuuss

PPaarrtt IIII((cchhaapptteerrss 66 –– 1122))

PPrreeppaarreedd ffoorr JJaavvaa PPrrooggrraammmmiinngg 9900..330011bbyy MMaarrjjaann TTrruuttsscchhll

mmttrruuttsscchh@@ccss..uummll..eedduu

Page 106: Presentation slides for Java Software Solutionsmtrutsch/teaching/class/90301/HandoutAllSlides...Presentation slides for Java Software Solutions ... Presentation slides for Java Software
Page 107: Presentation slides for Java Software Solutionsmtrutsch/teaching/class/90301/HandoutAllSlides...Presentation slides for Java Software Solutions ... Presentation slides for Java Software

1

Chapter 5: Enhancing Classes

Presentation slides for

Java Software SolutionsFoundations of Program Design

Second Edition

by John Lewis and William Loftus

Java Software Solutions is published by Addison-Wesley

Presentation slides are copyright 2000 by John Lewis and William Loftus. All rights reserved.Instructors using the textbook may use and modify these slides for pedagogical purposes.

2

Enhancing Classes

b We can now explore various aspects of classes and objectsin more detail

b Chapter 5 focuses on:• object references and aliases

• passing objects as parameters

• the static modifier

• nested classes

• interfaces and polymorphism

• events and listeners

• animation

Page 108: Presentation slides for Java Software Solutionsmtrutsch/teaching/class/90301/HandoutAllSlides...Presentation slides for Java Software Solutions ... Presentation slides for Java Software

2

3

References

b Recall from Chapter 2 that an object reference holds thememory address of an object

b Rather than dealing with arbitrary addresses, we oftendepict a reference graphically as a “pointer” to an object

ChessPiece bishop1 = new ChessPiece();

bishop1

4

Assignment Revisited

b The act of assignment takes a copy of a value and stores itin a variable

b For primitive types:

num2 = num1;

Before

num1

5

num2

12

After

num1

5

num2

5

Page 109: Presentation slides for Java Software Solutionsmtrutsch/teaching/class/90301/HandoutAllSlides...Presentation slides for Java Software Solutions ... Presentation slides for Java Software

3

5

Reference Assignment

b For object references, assignment copies the memorylocation:

bishop2 = bishop1;

Before

bishop1 bishop2

After

bishop1 bishop2

6

Aliases

b Two or more references that refer to the same object arecalled aliases of each other

b One object (and its data) can be accessed using differentvariables

b Aliases can be useful, but should be managed carefully

b Changing the object’s state (its variables) through onereference changes it for all of its aliases

Page 110: Presentation slides for Java Software Solutionsmtrutsch/teaching/class/90301/HandoutAllSlides...Presentation slides for Java Software Solutions ... Presentation slides for Java Software

4

7

Garbage Collection

b When an object no longer has any valid references to it, itcan no longer be accessed by the program

b It is useless, and therefore called garbage

b Java performs automatic garbage collection periodically,returning an object's memory to the system for future use

b In other languages, the programmer has the responsibilityfor performing garbage collection

Passing Objects to Methods

b Parameters in a Java method are passed by value

b This means that a copy of the actual parameter (the valuepassed in) is stored into the formal parameter (in themethod header)

b Passing parameters is essentially an assignment

b When an object is passed to a method, the actual parameterand the formal parameter become aliases of each other

Page 111: Presentation slides for Java Software Solutionsmtrutsch/teaching/class/90301/HandoutAllSlides...Presentation slides for Java Software Solutions ... Presentation slides for Java Software

5

Passing Objects to Methods

b What you do to a parameter inside a method may or maynot have a permanent effect (outside the method)

b See ParameterPassing.java (page 226)

b See ParameterTester.java (page 228)

b See Num.java (page 230)

b Note the difference between changing the reference andchanging the object that the reference points to

10

The static Modifier

b In Chapter 2 we discussed static methods (also called classmethods) that can be invoked through the class namerather than through a particular object

b For example, the methods of the Math class are static

b To make a method static, we apply the static modifier tothe method definition

b The static modifier can be applied to variables as well

b It associates a variable or method with the class rather thanan object

Page 112: Presentation slides for Java Software Solutionsmtrutsch/teaching/class/90301/HandoutAllSlides...Presentation slides for Java Software Solutions ... Presentation slides for Java Software

6

11

Static Methods

public static int triple (int num){ int result; result = num * 3; return result;}

class Helper

Because it is static, the method could be invoked as:

value = Helper.triple (5);

12

Static Methods

b The order of the modifiers can be interchanged, but byconvention visibility modifiers come first

b Recall that the main method is static; it is invoked by thesystem without creating an object

b Static methods cannot reference instance variables, becauseinstance variables don't exist until an object exists

b However, they can reference static variables or localvariables

Page 113: Presentation slides for Java Software Solutionsmtrutsch/teaching/class/90301/HandoutAllSlides...Presentation slides for Java Software Solutions ... Presentation slides for Java Software

7

13

Static Variables

b Static variables are sometimes called class variables

b Normally, each object has its own data space

b If a variable is declared as static, only one copy of thevariable exists

private static float price;

b Memory space for a static variable is created as soon as theclass in which it is declared is loaded

Static Variables

b All objects created from the class share access to the staticvariable

b Changing the value of a static variable in one objectchanges it for all others

b Static methods and variables often work together

b See CountInstances.java (page 233)

b See MyClass.java (page 234)

Page 114: Presentation slides for Java Software Solutionsmtrutsch/teaching/class/90301/HandoutAllSlides...Presentation slides for Java Software Solutions ... Presentation slides for Java Software

8

Nested Classes

b In addition to a class containing data and methods, it canalso contain other classes

b A class declared within another class is called a nested class

Outer Class

NestedClass

Nested Classes

b A nested class has access to the variables and methods ofthe outer class, even if they are declared private

b In certain situations this makes the implementation of theclasses easier because they can easily share information

b Furthermore, the nested class can be protected by the outerclass from external use

b This is a special relationship and should be used with care

Page 115: Presentation slides for Java Software Solutionsmtrutsch/teaching/class/90301/HandoutAllSlides...Presentation slides for Java Software Solutions ... Presentation slides for Java Software

9

Nested Classes

b A nested class produces a separate bytecode file

b If a nested class called Inside is declared in an outer classcalled Outside, two bytecode files will be produced:

Outside.class

Outside$Inside.class

b Nested classes can be declared as static, in which case theycannot refer to instance variables or methods

b A nonstatic nested class is called an inner class

Interfaces

b A Java interface is a collection of abstract methods andconstants

b An abstract method is a method header without a methodbody

b An abstract method can be declared using the modifierabstract, but because all methods in an interface areabstract, it is usually left off

b An interface is used to formally define a set of methods thata class will implement

Page 116: Presentation slides for Java Software Solutionsmtrutsch/teaching/class/90301/HandoutAllSlides...Presentation slides for Java Software Solutions ... Presentation slides for Java Software

10

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 in an

interface are givena definition (body)

A semicolon immediatelyfollows each method header

Interfaces

b An interface cannot be instantiated

b Methods in an interface have public visibility by default

b A class formally implements an interface by• stating so in the class header

• providing implementations for each abstract method in theinterface

b If a class asserts that it implements an interface, it mustdefine all methods in the interface or the compiler willproduce errors.

Page 117: Presentation slides for Java Software Solutionsmtrutsch/teaching/class/90301/HandoutAllSlides...Presentation slides for Java Software Solutions ... Presentation slides for Java Software

11

Interfaces

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

public void doThat () { // whatever }

// etc.}

implements is areserved word

Each method listedin Doable is

given a definition

Interfaces

b A class that implements an interface can implement othermethods as well

b See Speaker.java (page 236)

b See Philosopher.java (page 237)

b See Dog.java (page 238)

b A class can implement multiple interfaces

b The interfaces are listed in the implements clause,separated by commas

b The class must implement all methods in all interfaceslisted in the header

Page 118: Presentation slides for Java Software Solutionsmtrutsch/teaching/class/90301/HandoutAllSlides...Presentation slides for Java Software Solutions ... Presentation slides for Java Software

12

Polymorphism via Interfaces

b An interface name can be used as the type of an objectreference variable

Doable obj;

b The obj reference can be used to point to any object of anyclass that implements the Doable interface

b The version of doThis that the following line invokesdepends on the type of object that obj is referring to:

obj.doThis();

Polymorphism via Interfaces

b That reference is polymorphic, which can be defined as"having many forms"

b That line of code might execute different methods atdifferent times if the object that obj points to changes

b See Talking.java (page 240)

b Note that polymorphic references must be resolved at runtime; this is called dynamic binding

b Careful use of polymorphic references can lead to elegant,robust software designs

Page 119: Presentation slides for Java Software Solutionsmtrutsch/teaching/class/90301/HandoutAllSlides...Presentation slides for Java Software Solutions ... Presentation slides for Java Software

13

Interfaces

b The Java standard class library contains many interfacesthat are helpful in certain situations

b The Comparable interface contains an abstract methodcalled compareTo, which is used to compare two objects

b The String class implements Comparable which givesus the ability to put strings in alphabetical order

b The Iterator interface contains methods that allow theuser to move through a collection of objects easily

Events

b An event is an object that represents some activity to whichwe may want to respond

b For example, we may want our program to perform someaction when the following occurs:• the mouse is moved

• a mouse button is clicked

• the mouse is dragged

• a graphical button is clicked

• a keyboard key is pressed

• a timer expires

b Often events correspond to user actions, but not always

Page 120: Presentation slides for Java Software Solutionsmtrutsch/teaching/class/90301/HandoutAllSlides...Presentation slides for Java Software Solutions ... Presentation slides for Java Software

14

Events

b The Java standard class library contains several classesthat represent typical events

b Certain objects, such as an applet or a graphical button,generate (fire) an event when it occurs

b Other objects, called listeners, respond to events

b We can write listener objects to do whatever we want whenan event occurs

Events and Listeners

Generator

This object maygenerate an event

Listener

This object waits for andresponds to an event

Event

When an event occurs, the generator callsthe appropriate method of the listener,

passing an object that describes the event

Page 121: Presentation slides for Java Software Solutionsmtrutsch/teaching/class/90301/HandoutAllSlides...Presentation slides for Java Software Solutions ... Presentation slides for Java Software

15

Listener Interfaces

b We can create a listener object by writing a class thatimplements a particular listener interface

b The Java standard class library contains several interfacesthat correspond to particular event categories

b For example, the MouseListener interface containsmethods that correspond to mouse events

b After creating the listener, we add the listener to thecomponent that might generate the event to set up a formalrelationship between the generator and listener

Mouse Events

b The following are mouse events:• mouse pressed - the mouse button is pressed down

• mouse released - the mouse button is released

• mouse clicked - the mouse button is pressed and released

• mouse entered - the mouse pointer is moved over a particularcomponent

• mouse exited - the mouse pointer is moved off of a particularcomponent

b Any given program can listen for some, none, or all of these

b See Dots.java (page 246)

b See DotsMouseListener.java (page 248)

Page 122: Presentation slides for Java Software Solutionsmtrutsch/teaching/class/90301/HandoutAllSlides...Presentation slides for Java Software Solutions ... Presentation slides for Java Software

16

Mouse Motion Events

b The following are called mouse motion events:• mouse moved - the mouse is moved

• mouse dragged - the mouse is moved while the mouse button is helddown

b There is a corresponding MouseMotionListenerinterface

b One class can serve as both a generator and a listener

b One class can serve as a listener for multiple event types

b See RubberLines.java (page 249)

Key Events

b The following are called key events:• key pressed - a keyboard key is pressed down

• key released - a keyboard key is released

• key typed - a keyboard key is pressed and released

b The KeyListener interface handles key events

b Listener classes are often implemented as inner classes,nested within the component that they are listening to

b See Direction.java (page 253)

Page 123: Presentation slides for Java Software Solutionsmtrutsch/teaching/class/90301/HandoutAllSlides...Presentation slides for Java Software Solutions ... Presentation slides for Java Software

17

Animations

b An animation is a constantly changing series of pictures orimages that create the illusion of movement

b We can create animations in Java by changing a pictureslightly over time

b The speed of a Java animation is usually controlled by aTimer object

b The Timer class is defined in the javax.swing package

Animations

b A Timer object generates an ActionEvent every nmilliseconds (where n is set by the object creator)

b The ActionListener interface contains anactionPerformed method

b Whenever the timer expires (generating an ActionEvent)the animation can be updated

b See Rebound.java (page 258)

Page 124: Presentation slides for Java Software Solutionsmtrutsch/teaching/class/90301/HandoutAllSlides...Presentation slides for Java Software Solutions ... Presentation slides for Java Software
Page 125: Presentation slides for Java Software Solutionsmtrutsch/teaching/class/90301/HandoutAllSlides...Presentation slides for Java Software Solutions ... Presentation slides for Java Software

1

Chapter 6: Arrays and Vectors

Presentation slides for

Java Software SolutionsFoundations of Program Design

Second Edition

by John Lewis and William Loftus

Java Software Solutions is published by Addison-Wesley

Presentation slides are copyright 2000 by John Lewis and William Loftus. All rights reserved.Instructors using the textbook may use and modify these slides for pedagogical purposes.

2

Arrays and Vectors

b Arrays and vectors are objects that help us organize largeamounts of information

b Chapter 6 focuses on:• array declaration and use

• arrays of objects

• sorting elements in an array

• multidimensional arrays• the Vector class

• using arrays to manage graphics

Page 126: Presentation slides for Java Software Solutionsmtrutsch/teaching/class/90301/HandoutAllSlides...Presentation slides for Java Software Solutions ... Presentation slides for Java Software

2

3

Arrays

b An array is an ordered list of values

0 1 2 3 4 5 6 7 8 9

79 87 94 82 67 98 87 81 74 91

An array of size N is indexed from zero to N-1

scores

The entire arrayhas a single name

Each value has a numeric index

This array holds 10 values that are indexed from 0 to 9

4

Arrays

b A particular value in an array is referenced using the arrayname followed by the index in brackets

b For example, the expression

scores[2]

refers to the value 94 (which is the 3rd value in the array)

b That expression represents a place to store a single integer,and can be used wherever an integer variable can

b For example, it can be assigned a value, printed, or used ina calculation

Page 127: Presentation slides for Java Software Solutionsmtrutsch/teaching/class/90301/HandoutAllSlides...Presentation slides for Java Software Solutions ... Presentation slides for Java Software

3

5

Arrays

b An array stores multiple values of the same type

b That type can be primitive types or objects

b Therefore, we can create an array of integers, or an arrayof characters, or an array of String objects, etc.

b In Java, the array itself is an object

b Therefore the name of the array is a object referencevariable, and the array itself is instantiated separately

6

Declaring Arrays

b The scores array could be declared as follows:

int[] scores = new int[10];

b Note that the type of the array does not specify its size, buteach object of that type has a specific size

b The type of the variable scores is int[] (an array ofintegers)

b It is set to a new array object that can hold 10 integers

b See BasicArray.java (page 270)

Page 128: Presentation slides for Java Software Solutionsmtrutsch/teaching/class/90301/HandoutAllSlides...Presentation slides for Java Software Solutions ... Presentation slides for Java Software

4

7

Declaring Arrays

b Some examples of array declarations:

float[] prices = new float[500];

boolean[] flags;

flags = new boolean[20];

char[] codes = new char[1750];

8

Bounds Checking

b Once an array is created, it has a fixed size

b An index used in an array reference must specify a validelement

b That is, the index value must be in bounds (0 to N-1)

b The Java interpreter will throw an exception if an arrayindex is out of bounds

b This is called automatic bounds checking

Page 129: Presentation slides for Java Software Solutionsmtrutsch/teaching/class/90301/HandoutAllSlides...Presentation slides for Java Software Solutions ... Presentation slides for Java Software

5

Bounds Checking

b For example, if the array codes can hold 100 values, it canonly be indexed using the numbers 0 to 99

b If count has the value 100, then the following referencewill cause an ArrayOutOfBoundsException:

System.out.println (codes[count]);

b It’s common to introduce off-by-one errors when usingarrays

for (int index=0; index <= 100; index++)codes[index] = index*50 + epsilon;

problem

10

Bounds Checking

b Each array object has a public constant called length thatstores the size of the array

b It is referenced using the array name (just like any otherobject):

scores.length

b Note that length holds the number of elements, not thelargest index

b See ReverseNumbers.java (page 272)b See LetterCount.java (page 274)

Page 130: Presentation slides for Java Software Solutionsmtrutsch/teaching/class/90301/HandoutAllSlides...Presentation slides for Java Software Solutions ... Presentation slides for Java Software

6

11

Array Declarations Revisited

b The brackets of the array type can be associated with theelement type or with the name of the array

b Therefore the following declarations are equivalent:

float[] prices;

float prices[];

b The first format is generally more readable

12

Initializer Lists

b An initializer list can be used to instantiate and initialize anarray in one step

b The values are delimited by braces and separated bycommas

b Examples:

int[] units = {147, 323, 89, 933, 540,

269, 97, 114, 298, 476};

char[] letterGrades = {'A', 'B', 'C', 'D', 'F'};

Page 131: Presentation slides for Java Software Solutionsmtrutsch/teaching/class/90301/HandoutAllSlides...Presentation slides for Java Software Solutions ... Presentation slides for Java Software

7

13

Initializer Lists

b Note that when an initializer list is used:• the new operator is not used

• no size value is specified

b The size of the array is determined by the number of itemsin the initializer list

b An initializer list can only be used in the declaration of anarray

b See Primes.java (page 278)

14

Arrays as Parameters

b An entire array can be passed to a method as a parameter

b Like any other object, the reference to the array is passed,making the formal and actual parameters aliases of eachother

b Changing an array element in the method changes theoriginal

b An array element can be passed to a method as well, andwill follow the parameter passing rules of that element'stype

Page 132: Presentation slides for Java Software Solutionsmtrutsch/teaching/class/90301/HandoutAllSlides...Presentation slides for Java Software Solutions ... Presentation slides for Java Software

8

15

Arrays of Objects

b The elements of an array can be object references

b The following declaration reserves space to store 25references to String objects

String[] words = new String[25];

b It does NOT create the String objects themselves

b Each object stored in an array must be instantiatedseparately

b See GradeRange.java (page 280)

Command-Line Arguments

b The signature of the main method indicates that it takes anarray of String objects as a parameter

b These values come from command-line arguments that areprovided when the interpreter is invoked

b For example, the following invocation of the interpreterpasses an array of three String objects into main:

> java DoIt pennsylvania texas california

b These strings are stored at indexes 0-2 of the parameter

b See NameTag.java (page 281)

Page 133: Presentation slides for Java Software Solutionsmtrutsch/teaching/class/90301/HandoutAllSlides...Presentation slides for Java Software Solutions ... Presentation slides for Java Software

9

17

Arrays of Objects

b Objects can have arrays as instance variables

b Therefore, fairly complex structures can be created simplywith arrays and objects

b The software designer must carefully determine anorganization of data and objects that makes sense for thesituation

b See Tunes.java (page 282)

b See CDCollection.java (page 284)

b See CD.java (page 286)

18

Sorting

b Sorting is the process of arranging a list of items into aparticular order

b There must be some value on which the order is based

b There are many algorithms for sorting a list of items

b These algorithms vary in efficiency

b We will examine two specific algorithms:• Selection Sort

• Insertion Sort

Page 134: Presentation slides for Java Software Solutionsmtrutsch/teaching/class/90301/HandoutAllSlides...Presentation slides for Java Software Solutions ... Presentation slides for Java Software

10

19

Selection Sort

b The approach of Selection Sort:• select one value and put it in its final place in the sort list

• repeat for all other values

b In more detail:• find the smallest value in the list

• switch it with the value in the first position

• find the next smallest value in the list

• switch it with the value in the second position

• repeat until all values are placed

20

Selection Sort

b An example:

original: 3 9 6 1 2

smallest is 1: 1 9 6 3 2

smallest is 2: 1 2 6 3 9

smallest is 3: 1 2 3 6 9

smallest is 6: 1 2 3 6 9

b See SortGrades.java (page 289)

b See Sorts.java (page 290) -- the selectionSortmethod

Page 135: Presentation slides for Java Software Solutionsmtrutsch/teaching/class/90301/HandoutAllSlides...Presentation slides for Java Software Solutions ... Presentation slides for Java Software

11

21

Insertion Sort

b The approach of Insertion Sort:• Pick any item and insert it into its proper place in a sorted sublist

• repeat until all items have been inserted

b In more detail:• consider the first item to be a sorted sublist (of one item)

• insert the second item into the sorted sublist, shifting items asnecessary to make room to insert the new addition

• insert the third item into the sorted sublist (of two items), shifting asnecessary

• repeat until all values are inserted into their proper position

22

Insertion Sort

b An example:

original: 3 9 6 1 2

insert 9: 3 9 6 1 2

insert 6: 3 6 9 1 2

insert 1: 1 3 6 9 2

insert 2: 1 2 3 6 9

b See Sorts.java (page 290) -- the insertionSortmethod

Page 136: Presentation slides for Java Software Solutionsmtrutsch/teaching/class/90301/HandoutAllSlides...Presentation slides for Java Software Solutions ... Presentation slides for Java Software

12

23

Sorting Objects

b Integers have an inherent order, but the order of a set ofobjects must be defined by the person defining the class

b Recall that a Java interface can be used as a type name andguarantees that a particular class has implementedparticular methods

b We can use the Comparable interface to develop a genericsort for a set of objects

b See SortPhoneList.java (page 294)b See Contact.java (page 295)b See Sorts.java (page 290)

24

Comparing Sorts

b Both Selection and Insertion sorts are similar in efficiency

b The both have outer loops that scan all elements, and innerloops that compare the value of the outer loop with almostall values in the list

b Therefore approximately n2 number of comparisons aremade to sort a list of size n

b We therefore say that these sorts are of order n2

b Other sorts are more efficient: order n log2 n

Page 137: Presentation slides for Java Software Solutionsmtrutsch/teaching/class/90301/HandoutAllSlides...Presentation slides for Java Software Solutions ... Presentation slides for Java Software

13

25

Two-Dimensional Arrays

b A one-dimensional array stores a simple list of values

b A two-dimensional array can be thought of as a table ofvalues, with rows and columns

b A two-dimensional array element is referenced using twoindex values

b To be precise, a two-dimensional array in Java is an arrayof arrays

b See TwoDArray.java (page 299)

26

Multidimensional Arrays

b An array can have as many dimensions as needed, creatinga multidimensional array

b Each dimension subdivides the previous one into thespecified number of elements

b Each array dimension has its own length constant

b Because each dimension is an array of array references, thearrays within one dimension could be of different lengths

Page 138: Presentation slides for Java Software Solutionsmtrutsch/teaching/class/90301/HandoutAllSlides...Presentation slides for Java Software Solutions ... Presentation slides for Java Software

14

27

The Vector Class

b An object of class Vector is similar to an array in that itstores multiple values

b However, a vector• only stores objects• does not have the indexing syntax that arrays have

b The methods of the Vector class are used to interact withthe elements of a vector

b The Vector class is part of the java.util package

b See Beatles.java (page 304)

28

The Vector Class

b An important difference between an array and a vector isthat a vector can be thought of as a dynamic, able to changeits size as needed

b Each vector initially has a certain amount of memory spacereserved for storing elements

b If an element is added that doesn't fit in the existing space,more room is automatically acquired

Page 139: Presentation slides for Java Software Solutionsmtrutsch/teaching/class/90301/HandoutAllSlides...Presentation slides for Java Software Solutions ... Presentation slides for Java Software

15

29

The Vector Class

b The Vector class is implemented using an array

b Whenever new space is required, a new, larger array iscreated, and the values are copied from the original to thenew array

b To insert an element, existing elements are first copied, oneby one, to another position in the array

b Therefore, the implementation of Vector in the API is notvery efficient for inserting elements

Polygons and Polylines

b Arrays are often helpful in graphics processing

b Polygons and polylines are shapes that are defined byvalues stored in arrays

b A polyline is similar to a polygon except that its endpointsdo not meet, and it cannot be filled

b See Rocket.java (page 307)

b There is also a separate Polygon class that can be used todefine and draw a polygon

Page 140: Presentation slides for Java Software Solutionsmtrutsch/teaching/class/90301/HandoutAllSlides...Presentation slides for Java Software Solutions ... Presentation slides for Java Software

16

Saving Drawing State

b Each time the repaint method is called on an applet, thewindow is cleared prior to calling paint

b An array or vector can be used to store the objects drawn,and redraw them as necessary

b See Dots2.java (page 310)

Page 141: Presentation slides for Java Software Solutionsmtrutsch/teaching/class/90301/HandoutAllSlides...Presentation slides for Java Software Solutions ... Presentation slides for Java Software

1

Chapter 7: Inheritance

Presentation slides for

Java Software SolutionsFoundations of Program Design

Second Edition

by John Lewis and William Loftus

Java Software Solutions is published by Addison-Wesley

Presentation slides are copyright 2000 by John Lewis and William Loftus. All rights reserved.Instructors using the textbook may use and modify these slides for pedagogical purposes.

2

Inheritance

­ Another fundamental object-oriented technique is calledinheritance, which enhances software design and promotesreuse

­ Chapter 7 focuses on:• deriving new classes

• creating class hierarchies• the protected modifier

• polymorphism via inheritance

• inheritance used in graphical user interfaces

Page 142: Presentation slides for Java Software Solutionsmtrutsch/teaching/class/90301/HandoutAllSlides...Presentation slides for Java Software Solutions ... Presentation slides for Java Software

2

3

Inheritance

­ Inheritance allows a software developer to derive a newclass from an existing one

­ The existing class is called the parent class, or superclass, orbase class

­ The derived class is called the child class or subclass.

­ As the name implies, the child inherits characteristics of theparent

­ That is, the child class inherits the methods and datadefined for the parent class

4

Inheritance

­ Inheritance relationships are often shown graphically in aclass diagram, with the arrow pointing to the parent class

Inheritance should create an is-a relationship, meaningthe child is a more specific version of the parent

Vehicle

Car

Page 143: Presentation slides for Java Software Solutionsmtrutsch/teaching/class/90301/HandoutAllSlides...Presentation slides for Java Software Solutions ... Presentation slides for Java Software

3

5

Deriving Subclasses

­ In Java, we use the reserved word extends to establish aninheritance relationship

class Car extends Vehicle

{

// class contents

}

­ See Words.java (page 324)

­ See Book.java (page 325)

­ See Dictionary.java (page 326)

6

Controlling Inheritance

­ Visibility modifiers determine which class members getinherited and which do not

­ Variables and methods declared with public visibility areinherited, and those with private visibility are not

­ But public variables violate our goal of encapsulation

­ There is a third visibility modifier that helps in inheritancesituations: protected

Page 144: Presentation slides for Java Software Solutionsmtrutsch/teaching/class/90301/HandoutAllSlides...Presentation slides for Java Software Solutions ... Presentation slides for Java Software

4

7

The protected Modifier

­ The protected visibility modifier allows a member of abase class to be inherited into the child

­ But protected visibility provides more encapsulationthan public does

­ However, protected visibility is not as tightlyencapsulated as private visibility

­ The details of each modifier are given in Appendix F

8

The super Reference

­ Constructors are not inherited, even though they havepublic visibility

­ Yet we often want to use the parent's constructor to set upthe "parent's part" of the object

­ The super reference can be used to refer to the parentclass, and is often used to invoke the parent's constructor

­ See Words2.java (page 328)

­ See Book2.java (page 329)

­ See Dictionary2.java (page 330)

Page 145: Presentation slides for Java Software Solutionsmtrutsch/teaching/class/90301/HandoutAllSlides...Presentation slides for Java Software Solutions ... Presentation slides for Java Software

5

Single vs. Multiple Inheritance

­ Java supports single inheritance, meaning that a derivedclass can have only one parent class

­ Multiple inheritance allows a class to be derived from twoor more classes, inheriting the members of all parents

­ Collisions, such as the same variable name in two parents,have to be resolved

­ In most cases, the use of interfaces gives us the best aspectsof multiple inheritance without the overhead

10

Overriding Methods

­ A child class can override the definition of an inheritedmethod in favor of its own

­ That is, a child can redefine a method that it inherits fromits parent

­ The new method must have the same signature as theparent's method, but can have different code in the body

­ The type of the object executing the method determineswhich version of the method is invoked

Page 146: Presentation slides for Java Software Solutionsmtrutsch/teaching/class/90301/HandoutAllSlides...Presentation slides for Java Software Solutions ... Presentation slides for Java Software

6

Overriding Methods

­ See Messages.java (page 332)

­ See Thought.java (page 333)

­ See Advice.java (page 334)

­ Note that a parent method can be explicitly invoked usingthe super reference

­ If a method is declared with the final modifier, it cannotbe overridden

­ The concept of overriding can be applied to data (calledshadowing variables), there is generally no need for it

12

Overloading vs. Overriding

­ Don't confuse the concepts of overloading and overriding

­ Overloading deals with multiple methods in the same classwith the same name but different signatures

­ Overriding deals with two methods, one in a parent classand one in a child class, that have the same signature

­ Overloading lets you define a similar operation in differentways for different data

­ Overriding lets you define a similar operation in differentways for different object types

Page 147: Presentation slides for Java Software Solutionsmtrutsch/teaching/class/90301/HandoutAllSlides...Presentation slides for Java Software Solutions ... Presentation slides for Java Software

7

13

Class Hierarchies

­ A child class of one parent can be the parent of anotherchild, forming class hierarchies

Business

RetailBusiness ServiceBusiness

KMart Macys Kinkos

14

Class Hierarchies

­ Two children of the same parent are called siblings

­ Good class design puts all common features as high in thehierarchy as is reasonable

­ An inherited member is continually passed down the line

­ Class hierarchies often have to be extended and modified tokeep up with changing needs

­ There is no single class hierarchy that is appropriate for allsituations

Page 148: Presentation slides for Java Software Solutionsmtrutsch/teaching/class/90301/HandoutAllSlides...Presentation slides for Java Software Solutions ... Presentation slides for Java Software

8

15

The Object Class

­ A class called Object is defined in the java.langpackage of the Java standard class library

­ All classes are derived from the Object class

­ If a class is not explicitly defined to be the child of anexisting class, it is assumed to be the child of the Objectclass

­ The Object class is therefore the ultimate root of all classhierarchies

The Object Class

­ The Object class contains a few useful methods, which areinherited by all classes

­ For example, the toString method is defined in theObject class

­ Every time we have defined toString, we have actuallybeen overriding it

­ The toString method in the Object class is defined toreturn a string that contains the name of the object’s classand a hash value

Page 149: Presentation slides for Java Software Solutionsmtrutsch/teaching/class/90301/HandoutAllSlides...Presentation slides for Java Software Solutions ... Presentation slides for Java Software

9

The Object Class

­ That’s why the println method can call toString forany object that is passed to it – all objects are guaranteed tohave a toString method via inheritance

­ See Academia.java (page 339)­ See Student.java (page 340)­ See GradStudent.java (page 341)

­ The equals method of the Object class determines if tworeferences are aliases

­ You may choose to override equals to define equality insome other way

Abstract Classes

­ An abstract class is a placeholder in a class hierarchy thatrepresents a generic concept

­ An abstract class cannot be instantiated

­ We use the modifier abstract on the class header todeclare a class as abstract

­ An abstract class often contains abstract methods (like aninterface does), though it doesn’t have to

Page 150: Presentation slides for Java Software Solutionsmtrutsch/teaching/class/90301/HandoutAllSlides...Presentation slides for Java Software Solutions ... Presentation slides for Java Software

10

Abstract Classes

­ The child of an abstract class must override the abstractmethods of the parent, or it too will be considered abstract

­ An abstract method cannot be defined as final (because itmust be overridden) or static (because it has no definitionyet)

­ The use of abstract classes is a design decision; it helps usestablish common elements in a class that is to general toinstantiate

20

References and Inheritance

­ An object reference can refer to an object of its class, or toan object of any class related to it by inheritance

­ For example, if the Holiday class is used to derive a childclass called Christmas, then a Holiday reference couldactually be used to point to a Christmas object

Holiday

Christmas

Holiday day;day = new Christmas();

Page 151: Presentation slides for Java Software Solutionsmtrutsch/teaching/class/90301/HandoutAllSlides...Presentation slides for Java Software Solutions ... Presentation slides for Java Software

11

21

References and Inheritance

­ Assigning a predecessor object to an ancestor reference isconsidered to be a widening conversion, and can beperformed by simple assignment

­ Assigning an ancestor object to a predecessor reference canalso be done, but it is considered to be a narrowingconversion and must be done with a cast

­ The widening conversion is the most useful

22

Polymorphism via Inheritance

­ We saw in Chapter 5 how an interface can be used to createa polymorphic reference

­ Recall that a polymorphic reference is one which can referto different types of objects at different times

­ Inheritance can also be used as a basis of polymorphism

­ An object reference can refer to one object at one time,then it can be changed to refer to another object (related byinheritance) at another time

Page 152: Presentation slides for Java Software Solutionsmtrutsch/teaching/class/90301/HandoutAllSlides...Presentation slides for Java Software Solutions ... Presentation slides for Java Software

12

Polymorphism via Inheritance

­ Suppose the Holiday class has a method calledcelebrate, and the Christmas class overrode it

­ Now consider the following invocation:

day.celebrate();

­ If day refers to a Holiday object, it invokes the Holidayversion of celebrate; if it refers to a Christmas object,it invokes the Christmas version

24

Polymorphism via Inheritance

­ It is the type of the object being referenced, not thereference type, that determines which method is invoked

­ Note that, if an invocation is in a loop, the exact same line ofcode could execute different methods at different times

­ Polymorphic references are therefore resolved at run-time,not during compilation

Page 153: Presentation slides for Java Software Solutionsmtrutsch/teaching/class/90301/HandoutAllSlides...Presentation slides for Java Software Solutions ... Presentation slides for Java Software

13

Polymorphism via Inheritance

­ Consider the following class hierarchy:

StaffMember

Volunteer Employee

Executive Hourly

Polymorphism via Inheritance

­ Now consider the task of paying all employees

­ See Firm.java (page 345)

­ See Staff.java (page 346)

­ See StaffMember.java (page 348)

­ See Volunteer.java (page 349)

­ See Employee.java (page 351)

­ See Executive.java (page 352)

­ See Hourly.java (page 353)

Page 154: Presentation slides for Java Software Solutionsmtrutsch/teaching/class/90301/HandoutAllSlides...Presentation slides for Java Software Solutions ... Presentation slides for Java Software

14

27

Indirect Access

­ An inherited member can be referenced directly by name inthe child class, as if it were declared in the child class

­ But even if a method or variable is not inherited by a child,it can still be accessed indirectly through parent methods

­ See FoodAnalysis.java (page 355)

­ See FoodItem.java (page 356)

­ See Pizza.java (page 357)

Interface Hierarchies

­ Inheritance can be applied to interfaces as well as classes

­ One interface can be used as the parent of another

­ The child interface inherits all abstract methods of theparent

­ A class implementing the child interface must define allmethods from both the parent and child interfaces

­ Note that class hierarchies and interface hierarchies aredistinct (the do not overlap)

Page 155: Presentation slides for Java Software Solutionsmtrutsch/teaching/class/90301/HandoutAllSlides...Presentation slides for Java Software Solutions ... Presentation slides for Java Software

15

Applets and Inheritance

­ An applet is an excellent example of inheritance

­ Recall that when we define an applet, we extend theApplet class

­ The Applet class already handles all the details aboutapplet creation and execution, including the interactionwith a web browser

­ Our applet classes only have to deal with issues thatspecifically relate to what our particular applet will do

Extending Event Adapter Classes

­ In Chapter 5 we discussed the creation of listener classes byimplementing a particular interface (such asMouseListener interface)

­ A listener can also be created by extending a special adapterclass of the Java class library

­ Each listener interface has a corresponding adapter class(such as the MouseAdapter class)

­ Each adapter class implements the corresponding listenerand provides empty method definitions

Page 156: Presentation slides for Java Software Solutionsmtrutsch/teaching/class/90301/HandoutAllSlides...Presentation slides for Java Software Solutions ... Presentation slides for Java Software

16

Extending Event Adapter Classes

­ When you derive a listener class from an adapter class, youoverride any event methods of interest (such as themouseClicked method)

­ Note that this avoids the need to create empty definitionsfor unused events

­ See OffCenter.java (page 360)

GUI Components

­ A GUI component is an object that represents a visualentity in an graphical user interface (such as a button orslider)

­ Components can generate events to which listener objectscan respond

­ For example, an applet is a component that can generatemouse events

­ An applet is also a special kind of component, called acontainer, in which other components can be placed

Page 157: Presentation slides for Java Software Solutionsmtrutsch/teaching/class/90301/HandoutAllSlides...Presentation slides for Java Software Solutions ... Presentation slides for Java Software

17

GUI Components

­ See Fahrenheit.java (page 363)

­ Components are organized into an inheritance classhierarchy so that they can easily share characteristics

­ When we define certain methods, such as the paintmethod of an applet, we are actually overriding a methoddefined in the Component class, which is ultimatelyinherited into the Applet class

­ See Doodle.java (page 367)

­ See DoodleCanvas.java (page 369)

Page 158: Presentation slides for Java Software Solutionsmtrutsch/teaching/class/90301/HandoutAllSlides...Presentation slides for Java Software Solutions ... Presentation slides for Java Software
Page 159: Presentation slides for Java Software Solutionsmtrutsch/teaching/class/90301/HandoutAllSlides...Presentation slides for Java Software Solutions ... Presentation slides for Java Software

1

Chapter 8: Exceptions and I/O Streams

Presentation slides for

Java Software SolutionsFoundations of Program Design

Second Edition

by John Lewis and William Loftus

Java Software Solutions is published by Addison-Wesley

Presentation slides are copyright 2000 by John Lewis and William Loftus. All rights reserved.Instructors using the textbook may use and modify these slides for pedagogical purposes.

2

Exceptions and I/O Streams

b We can now further explore two related topics: exceptionsand input / output streams

b Chapter 8 focuses on:• the try-catch statement

• exception propagation

• creating and throwing exceptions

• types of I/O streams

• Keyboard class processing

• reading and writing text files

• object serialization

Page 160: Presentation slides for Java Software Solutionsmtrutsch/teaching/class/90301/HandoutAllSlides...Presentation slides for Java Software Solutions ... Presentation slides for Java Software

2

3

Exceptions

b An exception is an object that describes an unusual orerroneous situation

b Exceptions are thrown by a program, and may be caughtand handled by another part of the program

b A program can therefore be separated into a normalexecution flow and an exception execution flow

b An error is also represented as an object in Java, butusually represents a unrecoverable situation and should notbe caught

4

Exception Handling

b A program can deal with an exception in one of three ways:• ignore it

• handle it where it occurs

• handle it an another place in the program

b The manner in which an exception is processed is animportant design consideration

Page 161: Presentation slides for Java Software Solutionsmtrutsch/teaching/class/90301/HandoutAllSlides...Presentation slides for Java Software Solutions ... Presentation slides for Java Software

3

5

Exception Handling

b If an exception is ignored by the program, the program willterminate and produce an appropriate message

b The message includes a call stack trace that indicates onwhich line the exception occurred

b The call stack trace also shows the method call trail thatlead to the execution of the offending line

b See Zero.java (page 379)

6

The try Statement

b To process an exception when it occurs, the line that throwsthe exception is executed within a try block

b A try block is followed by one or more catch clauses, whichcontain code to process an exception

b Each catch clause has an associated exception type

b When an exception occurs, processing continues at the firstcatch clause that matches the exception type

b See ProductCodes.java (page 381)

Page 162: Presentation slides for Java Software Solutionsmtrutsch/teaching/class/90301/HandoutAllSlides...Presentation slides for Java Software Solutions ... Presentation slides for Java Software

4

7

The finally Clause

b A try statement can have an optional clause designated bythe reserved word finally

b If no exception is generated, the statements in the finallyclause are executed after the statements in the try blockcomplete

b Also, if an exception is generated, the statements in thefinally clause are executed after the statements in theappropriate catch clause complete

8

Exception Propagation

b If it is not appropriate to handle the exception where itoccurs, it can be handled at a higher level

b Exceptions propagate up through the method callinghierarchy until they are caught and handled or until theyreach the outermost level

b A try block that contains a call to a method in which anexception is thrown can be used to catch that exception

b See Propagation.java (page 384)

b See ExceptionScope.java (page 385)

Page 163: Presentation slides for Java Software Solutionsmtrutsch/teaching/class/90301/HandoutAllSlides...Presentation slides for Java Software Solutions ... Presentation slides for Java Software

5

9

The throw Statement

b A programmer can define an exception by extending theappropriate class

b Exceptions are thrown using the throw statement

b See CreatingExceptions.java (page 388)

b See OutOfRangeException.java (page 389)

b Usually a throw statement is nested inside an if statementthat evaluates the condition to see if the exception should bethrown

10

Checked Exceptions

b An exception is either checked or unchecked

b A checked exception can only be thrown within a try blockor within a method that is designated to throw thatexception

b The compiler will complain if a checked exception is nothandled appropriately

b An unchecked exception does not require explicit handling,though it could be processed that way

Page 164: Presentation slides for Java Software Solutionsmtrutsch/teaching/class/90301/HandoutAllSlides...Presentation slides for Java Software Solutions ... Presentation slides for Java Software

6

I/O Streams

b A stream is a sequence of bytes that flow from a source to adestination

b In a program, we read information from an input streamand write information to an output stream

b A program can manage multiple streams at a time

b The java.io package contains many classes that allow us todefine various streams with specific characteristics

I/O Stream Categories

b The classes in the I/O package divide input and outputstreams into other categories

b An I/O stream is either a• character stream, which deals with text data

• byte stream, which deal with byte data

b An I/O stream is also either a• data stream, which acts as either a source or destination

• processing stream, which alters or manages information in thestream

Page 165: Presentation slides for Java Software Solutionsmtrutsch/teaching/class/90301/HandoutAllSlides...Presentation slides for Java Software Solutions ... Presentation slides for Java Software

7

Standard I/O

b There are three standard I/O streams:• standard input – defined by System.in

• standard output – defined by System.out

• standard error – defined by System.err

b We use System.out when we execute printlnstatements

b System.in is declared to be a generic InputStreamreference, and therefore usually must be mapped to a moreuseful stream with specific characteristics

The Keyboard Class

b The Keyboard class was written by the authors of yourtextbook to facilitate reading data from standard input

b Now we can examine the processing of the Keyboard classin more detail

b The Keyboard class:• declares a useful standard input stream

• handles exceptions that may be thrown

• parses input lines into separate values

• converts input stings into the expected type

• handles conversion problems

Page 166: Presentation slides for Java Software Solutionsmtrutsch/teaching/class/90301/HandoutAllSlides...Presentation slides for Java Software Solutions ... Presentation slides for Java Software

8

The Standard Input Stream

b The Keyboard class declares the following input stream:

InputStreamReader isr =

new InputStreamReader (System.in)

BufferedReader stdin = new BufferedReader (isr);

b The InputStreamReader object converts the originalbyte stream into a character stream

b The BufferedReader object allows us to use thereadLine method to get an entire line of input

Text Files

b Information can be read from and written to text files bydeclaring and using the correct I/O streams

b The FileReader class represents an input file containingcharacter data

b See Inventory.java (page 397)

b See InventoryItem.java (page 400)

b The FileWriter class represents a text output file

b See TestData.java (page 402)

Page 167: Presentation slides for Java Software Solutionsmtrutsch/teaching/class/90301/HandoutAllSlides...Presentation slides for Java Software Solutions ... Presentation slides for Java Software

9

Object Serialization

b Object serialization is the act of saving an object, and itscurrent state, so that it can be used again in anotherprogram

b The idea that an object can “live” beyond the programthat created it is called persistence

b Object serialization is accomplished using the classesObjectOutputStream and ObjectInputStream

b Serialization takes into account any other objects that arereferenced by an object being serialized, saving them too

Page 168: Presentation slides for Java Software Solutionsmtrutsch/teaching/class/90301/HandoutAllSlides...Presentation slides for Java Software Solutions ... Presentation slides for Java Software
Page 169: Presentation slides for Java Software Solutionsmtrutsch/teaching/class/90301/HandoutAllSlides...Presentation slides for Java Software Solutions ... Presentation slides for Java Software

1

Chapter 9: Graphical User Interfaces

Presentation slides for

Java Software SolutionsFoundations of Program Design

Second Edition

by John Lewis and William Loftus

Java Software Solutions is published by Addison-Wesley

Presentation slides are copyright 2000 by John Lewis and William Loftus. All rights reserved.Instructors using the textbook may use and modify these slides for pedagogical purposes.

2

Graphical User Interfaces

­ We can now explore the creation of graphical userinterfaces in more detail

­ Chapter 9 focuses on:• GUI infrastructure

• containers

• using graphics in applications

• Swing components

• layout managers

Page 170: Presentation slides for Java Software Solutionsmtrutsch/teaching/class/90301/HandoutAllSlides...Presentation slides for Java Software Solutions ... Presentation slides for Java Software

2

GUI Overview

­ To create a Java GUI, we need to understand:• events

• listeners

• containers

• components

• layout managers

• special features

­ In Chapters 5 and 7 we introduced events and listeners, aswell as GUI components from the java.awt package

­ In this chapter we will focus on Swing components

AWT vs. Swing

­ Early Java development used graphic classes defined in theAbstract Windowing Toolkit (AWT)

­ With Java 2, Swing classes were introduced

­ Many AWT components have improved Swingcounterparts

­ For example, the AWT Button class corresponds to amore versatile Swing class called JButton

­ However, Swing does not generally replace the AWT; westill use AWT events and the underlying AWT eventprocessing model

Page 171: Presentation slides for Java Software Solutionsmtrutsch/teaching/class/90301/HandoutAllSlides...Presentation slides for Java Software Solutions ... Presentation slides for Java Software

3

Containers

­ A container is a special component that can hold othercomponents

­ The AWT Applet class, as well as the Swing JAppletclass, are containers

­ Other containers include:• panels

• frames

• dialog boxes

Graphics in Applications

­ Applets must be displayed through a browser or throughthe appletviewer

­ Similarly, a panel must be displayed within the context ofanother container

­ A frame is a container that is free standing and can bepositioned anywhere on the screen

­ Frames give us the ability to do graphics and GUIs throughapplications (not just applets)

Page 172: Presentation slides for Java Software Solutionsmtrutsch/teaching/class/90301/HandoutAllSlides...Presentation slides for Java Software Solutions ... Presentation slides for Java Software

4

Window Events

­ Because a frame is a free standing window, we must nowaddress window events

­ Specifically, we must be able to handle a window closingevent

­ Frames have an icon in the corner of the window to close it

­ Clicking it will cause the windowClosing method of awindow listener object to be invoked

­ See GenericWindowListener.java (page 412)­ See ShowFrames.java (page 413)

Swing Components

­ There are various Swing GUI components that we canincorporate into our software:• labels (including images)

• text fields and text areas

• buttons

• check boxes

• radio buttons

• menus

• combo boxes

• and many more…

­ Using the proper components for the situation is animportant part of GUI design

Page 173: Presentation slides for Java Software Solutionsmtrutsch/teaching/class/90301/HandoutAllSlides...Presentation slides for Java Software Solutions ... Presentation slides for Java Software

5

Labels and Image Icons

­ A label is used to provide information to the user or to adddecoration to the GUI

­ A Swing label is defined by the JLabel class

­ It can incorporate an image defined by the ImageIconclass

­ The alignment and relative positioning of the text andimage of a label can be explicitly set

­ See ShowLabels.java (page 416)­ See LabelDemo.java (page 417)

Buttons

­ GUI buttons fall into various categories:

• push button – a generic button that initiates some action

• check box – a button that can be toggled on or off

• radio buttons – a set of buttons that provide a set of mutuallyexclusive options

­ Radio buttons must work as a group; only one can betoggled on at a time

­ Radio buttons are grouped using the ButtonGroup class

Page 174: Presentation slides for Java Software Solutionsmtrutsch/teaching/class/90301/HandoutAllSlides...Presentation slides for Java Software Solutions ... Presentation slides for Java Software

6

Buttons

­ Push buttons and radio buttons generate action eventswhen pushed or toggled

­ Check boxes generate item state changed events whentoggled

­ See Quotes.java (page 419)

­ See QuotesControls.java (page 420)

Combo Boxes

­ A combo box displays a particular option with a pull downmenu from which the user can choose a different option

­ The currently selected option is shown in the combo box

­ A combo box can be editable, so that the user can type theiroption directly into the box

­ See JukeBox.java (page 425)

­ See JukeBoxControls.java (page 426)

Page 175: Presentation slides for Java Software Solutionsmtrutsch/teaching/class/90301/HandoutAllSlides...Presentation slides for Java Software Solutions ... Presentation slides for Java Software

7

Layout Managers

­ A layout manager is an object that determines the mannerin which components are displayed in a container

­ There are several predefined layout managers defined inthe Java standard class library:

Defined in the AWT

Defined in Swing

Flow LayoutBorder LayoutCard LayoutGrid LayoutGridBag Layout

Box Layout

Overlay Layout

Layout Managers

­ Every container has a default layout manager, but we canalso explicitly set the layout manager for a container

­ Each layout manager has its own particular rulesgoverning how the components will be arranged

­ Some layout managers pay attention to a component'spreferred size or alignment, and others do not

­ The layout managers attempt to adjust the layout ascomponents are added and as containers are resized

Page 176: Presentation slides for Java Software Solutionsmtrutsch/teaching/class/90301/HandoutAllSlides...Presentation slides for Java Software Solutions ... Presentation slides for Java Software

8

Flow Layout

­ A flow layout puts as many components on a row aspossible, then moves to the next row

­ Rows are created as needed to accommodate all of thecomponents

­ Components are displayed in the order they are added tothe container

­ The horizontal and vertical gaps between the componentscan be explicitly set

Border Layout

­ A border layout defines five areas into which componentscan be added

North

South

Center EastWest

Page 177: Presentation slides for Java Software Solutionsmtrutsch/teaching/class/90301/HandoutAllSlides...Presentation slides for Java Software Solutions ... Presentation slides for Java Software

9

Border Layout

­ Each area displays one component (which could be anothercontainer)

­ Each of the four outer areas enlarge as needed toaccommodate the component added to them

­ If nothing is added to the outer areas, they take up no spaceand other areas expand to fill the void

­ The center area expands to fill space as needed

Box Layout

­ A box layout organizes components either horizontally (inone row) or vertically (in one column)

­ Special rigid areas can be added to force a certain amountof spacing between components

­ By combining multiple containers using box layout, manydifferent configurations can be created

­ Multiple containers with box layouts are often preferred toone container that uses the more complicated gridbaglayout manager

Page 178: Presentation slides for Java Software Solutionsmtrutsch/teaching/class/90301/HandoutAllSlides...Presentation slides for Java Software Solutions ... Presentation slides for Java Software

10

Special Features

­ Swing components offer a variety of other features

­ Tool tips provide a short pop-up description when themouse cursor rests momentarily on a component

­ Borders around each component can be stylized in variousways

­ Keyboard shortcuts called mnemonics can be added tographical objects such as buttons

GUI Design

­ In addition to the tools necessary to put a GUI together, wemust also focus on solving the problem

­ The GUI designer should:

• Know the user and their needs

• Prevent user errors whenever possible

• Optimize user abilities and make information readily available

• Be consistent with placement of components and color schemes

Page 179: Presentation slides for Java Software Solutionsmtrutsch/teaching/class/90301/HandoutAllSlides...Presentation slides for Java Software Solutions ... Presentation slides for Java Software

1

Chapter 10: Software Engineering

Presentation slides for

Java Software SolutionsFoundations of Program Design

Second Edition

by John Lewis and William Loftus

Java Software Solutions is published by Addison-Wesley

Presentation slides are copyright 2000 by John Lewis and William Loftus. All rights reserved.Instructors using the textbook may use and modify these slides for pedagogical purposes.

2

Software Engineering

b The quality of the software we create is a direct result ofthe process we follow to develop it

b Chapter 10 focuses on:• software development models

• the software life cycle

• linear and iterative development approaches

• an evolutionary approach to object-oriented development

Page 180: Presentation slides for Java Software Solutionsmtrutsch/teaching/class/90301/HandoutAllSlides...Presentation slides for Java Software Solutions ... Presentation slides for Java Software

2

3

The Program Life Cycle

b The overall life cycle of a program includes use andmaintenance:

UseDevelopment

Maintenance

4

Maintenance

b Maintenance tasks include any modifications to an existingprogram

b It includes defect removal and enhancements

b The characteristics of a program that make it easy todevelop also make it easy to maintain

b Maintenance efforts tend to far outweigh the developmenteffort in today’s software

b Small increases in effort at the development stage cangreatly reduce maintenance tasks

Page 181: Presentation slides for Java Software Solutionsmtrutsch/teaching/class/90301/HandoutAllSlides...Presentation slides for Java Software Solutions ... Presentation slides for Java Software

3

5

Development vs. Maintenance

Use andMaintenance

Development

6

Development and Maintenance Effort

Development Maintenance

Development Maintenance

Small increases in development effort canreduce maintenance effort

Page 182: Presentation slides for Java Software Solutionsmtrutsch/teaching/class/90301/HandoutAllSlides...Presentation slides for Java Software Solutions ... Presentation slides for Java Software

4

7

Development Process Models

b Too many programmers follow a build-and-fix approach

b They write a program and modify it until it is functional,without regard to system design

b Errors are haphazardly addressed as they are discovered

b It is not really a development model at all

8

The Build-and-Fix Approach

Writeprogram

Modifyprogram

Page 183: Presentation slides for Java Software Solutionsmtrutsch/teaching/class/90301/HandoutAllSlides...Presentation slides for Java Software Solutions ... Presentation slides for Java Software

5

9

The Waterfall Model

b The waterfall model was developed in the mid 1970s

b Activities that must be specifically addressed duringdevelopment include:• Establishing clear and unambiguous requirements

• Creating a clean design from the requirements

• Implementing the design

• Testing the implementation

b Originally it was proposed as a linear model, with little orno backtracking

b It is a nice goal, but is generally unrealistic

10

The Waterfall Model

Establish requirements

Create design

Implement code

Test system

Page 184: Presentation slides for Java Software Solutionsmtrutsch/teaching/class/90301/HandoutAllSlides...Presentation slides for Java Software Solutions ... Presentation slides for Java Software

6

11

An Iterative Process

b Allows the developer to cycle through the differentdevelopment stages

b Essentially the waterfall model with backtracking

b However backtracking should not be used irresponsibly

b It should be used as a technique available to the developerin order to deal with unexpected problems that may arise inlater stages of development

12

An Iterative Development Process

Establishrequirements

Createdesign

Implementcode

Testsystem

Page 185: Presentation slides for Java Software Solutionsmtrutsch/teaching/class/90301/HandoutAllSlides...Presentation slides for Java Software Solutions ... Presentation slides for Java Software

7

13

Prototype

b A prototype is a program created to explore a particularconcept

b More useful, time-effective, and cost-effective than merelyacting on an assumption that may later backfire

b Usually created to communicate to the client:• a particular task

• the feasibility of a requirement

• a user interface

b A way of validating requirements

14

Evaluation

b The results of each stage should be evaluated carefullyprior to going on to the next stage

b Before moving on to the design, for example, therequirements should be evaluated to ensure completeness,consistency, and clarity

b A design evaluation should ensure that each requirementwas adequately addressed

b Prior to testing, the implementation should be give athorough code walkthrough

Page 186: Presentation slides for Java Software Solutionsmtrutsch/teaching/class/90301/HandoutAllSlides...Presentation slides for Java Software Solutions ... Presentation slides for Java Software

8

15

Testing Techniques

b Generally, the goal of testing is to find errors

b It is often called defect testing

b A good test will uncover problems in a program

b A test case includes• a set of inputs

• user actions or other initial conditions

• expected output

b It is not feasible to exhaust every possible case

16

Black-Box Testing

b Black-box testing maps a set of specific inputs to a set ofexpected outputs

b An equivalence category is a collection of input sets

b Two input sets belong to the same equivalence category ifthere is no reason to believe that if one works, the other willnot

b Therefore testing one input set essentially tests the entirecategory

Page 187: Presentation slides for Java Software Solutionsmtrutsch/teaching/class/90301/HandoutAllSlides...Presentation slides for Java Software Solutions ... Presentation slides for Java Software

9

17

White-Box Testing

b White-box testing is also referred to as glass-box testing

b It focuses on the internal logic such as the implementationof a method

b Statement coverage guarantees that all statements in amethod are executed

b Condition coverage guarantes that all paths through amethod are executed

18

An Evolutionary Development Model

b We will now divide the process of design into• architectural design - primary classes and interaction

• detailed design - specific classes, methods, and algorithms

b This allows us to create a refinement cycle

b Each refinement focuses on one aspect of the system

b As each refinement is addressed, the system evolves

Page 188: Presentation slides for Java Software Solutionsmtrutsch/teaching/class/90301/HandoutAllSlides...Presentation slides for Java Software Solutions ... Presentation slides for Java Software

10

19

An Evolutionary Development Model

Establishrequirements

Architecturaldesign

Establishrefinement

scope

Unit andintegration test

Implementation

System test

Identify classes& objects

Identifyrelationships

Detaileddesign

20

Refinement Cycle

b First, we establish refinement scope to define the specificnature of the next refinement

b Such as:• the user interface

• a particular algorithm

• a particular requirement

b Choosing the most appropriate next refinement isimportant and requires experience

Page 189: Presentation slides for Java Software Solutionsmtrutsch/teaching/class/90301/HandoutAllSlides...Presentation slides for Java Software Solutions ... Presentation slides for Java Software

11

21

Refinement Cycle

b Next, we identify classes and objects

b The ones that relate to the current refinement

b These may overlap with other refinements

b Can often define by focusing on the roles they play in thesystem

b Consider reusing existing classes

22

Refinement Cycle

b Then we identify relationships among classes

b Inheritance (is-a) relationships

b The uses relationship establishes another kind of bondbetween classes• Class A uses class B in some way

• Can express cardinality

• Example: A Car has (uses) four wheels

Page 190: Presentation slides for Java Software Solutionsmtrutsch/teaching/class/90301/HandoutAllSlides...Presentation slides for Java Software Solutions ... Presentation slides for Java Software

12

23

Refinement Cycle

b Finally, detailed design, implementation and test

b Design of specific methods and their translation into code

b A unit test focuses on one particular component, such as amethod or class

b An integration test focuses on the interaction betweencomponents

The PaintBox Project

b We can explore the evolutionary development model usinga larger project

b The PaintBox program will allow the user to createdrawings with various shapes and colors

b After establishing the requirements, the followingrefinement steps were established:• create the basic user interface• allow the user to draw shapes and change color• allow the user to select, move, and fill shapes• allow the user to edit the dimensions of shapes• allow the user to save and reload drawings

Page 191: Presentation slides for Java Software Solutionsmtrutsch/teaching/class/90301/HandoutAllSlides...Presentation slides for Java Software Solutions ... Presentation slides for Java Software

13

PaintBox Refinement 1

b The first refinement establishes the basic user interface

b See PaintBox.java

b See PaintFrame.java

b See ButtonPanel.java

b See DrawingPanel.java

PaintBox Refinement 2

b See PaintBox.java

b See PaintFrame.java

b See ButtonPanel.java

b See DrawingPanel.java

b See Shape.java

b See Line.java

b See BoundedShape.java

b See Rect.java

b See Oval.java

b See Poly.java

b The second refinement allows the user to draw shapes andchange colors

Page 192: Presentation slides for Java Software Solutionsmtrutsch/teaching/class/90301/HandoutAllSlides...Presentation slides for Java Software Solutions ... Presentation slides for Java Software
Page 193: Presentation slides for Java Software Solutionsmtrutsch/teaching/class/90301/HandoutAllSlides...Presentation slides for Java Software Solutions ... Presentation slides for Java Software

1

Chapter 11: Recursion

Presentation slides for

Java Software SolutionsFoundations of Program Design

Second Edition

by John Lewis and William Loftus

Java Software Solutions is published by Addison-Wesley

Presentation slides are copyright 2000 by John Lewis and William Loftus. All rights reserved.Instructors using the textbook may use and modify these slides for pedagogical purposes.

2

Recursion

b Recursion is a fundamental programming technique thatcan provide an elegant solution certain kinds of problems

b Chapter 11 focuses on:• thinking in a recursive manner

• programming in a recursive manner

• the correct use of recursion

• recursion examples

Page 194: Presentation slides for Java Software Solutionsmtrutsch/teaching/class/90301/HandoutAllSlides...Presentation slides for Java Software Solutions ... Presentation slides for Java Software

2

3

Recursive Thinking

b A recursive definition is one which uses the word or conceptbeing defined in the definition itself

b When defining an English word, a recursive definition isoften not helpful

b But in other situations, a recursive definition can be anappropriate way to express a concept

b Before applying recursion to programming, it is best topractice thinking recursively

4

Recursive Definitions

b Consider the following list of numbers:

24, 88, 40, 37

b Such a list can be defined as

A LIST is a: number or a: number comma LIST

b That is, a LIST is defined to be a single number, or anumber followed by a comma followed by a LIST

b The concept of a LIST is used to define itself

Page 195: Presentation slides for Java Software Solutionsmtrutsch/teaching/class/90301/HandoutAllSlides...Presentation slides for Java Software Solutions ... Presentation slides for Java Software

3

5

Recursive Definitions

b The recursive part of the LIST definition is used severaltimes, terminating with the non-recursive part:

number comma LIST

24 , 88, 40, 37

number comma LIST

88 , 40, 37

number comma LIST

40 , 37

number

37

6

Infinite Recursion

b All recursive definitions have to have a non-recursive part

b If they didn't, there would be no way to terminate therecursive path

b Such a definition would cause infinite recursion

b This problem is similar to an infinite loop, but the non-terminating "loop" is part of the definition itself

b The non-recursive part is often called the base case

Page 196: Presentation slides for Java Software Solutionsmtrutsch/teaching/class/90301/HandoutAllSlides...Presentation slides for Java Software Solutions ... Presentation slides for Java Software

4

7

Recursive Definitions

b N!, for any positive integer N, is defined to be the productof all integers between 1 and N inclusive

b This definition can be expressed recursively as:

1! = 1

N! = N * (N-1)!

b The concept of the factorial is defined in terms of anotherfactorial

b Eventually, the base case of 1! is reached

8

Recursive Definitions

5!

5 * 4!

4 * 3!

3 * 2!

2 * 1!

1

2

6

24

120

Page 197: Presentation slides for Java Software Solutionsmtrutsch/teaching/class/90301/HandoutAllSlides...Presentation slides for Java Software Solutions ... Presentation slides for Java Software

5

9

Recursive Programming

b A method in Java can invoke itself; if set up that way, it iscalled a recursive method

b The code of a recursive method must be structured tohandle both the base case and the recursive case

b Each call to the method sets up a new executionenvironment, with new parameters and local variables

b As always, when the method completes, control returns tothe method that invoked it (which may be an earlierinvocation of itself)

10

Recursive Programming

b Consider the problem of computing the sum of all thenumbers between 1 and any positive integer N

b This problem can be recursively defined as:

i = 1

N

i = 1

N-1

i = 1

N-2

= N + = N + (N-1) +

= etc.

Page 198: Presentation slides for Java Software Solutionsmtrutsch/teaching/class/90301/HandoutAllSlides...Presentation slides for Java Software Solutions ... Presentation slides for Java Software

6

11

Recursive Programming

main

sum

sum

sum

sum(3)

sum(1)

sum(2)

result = 1

result = 3

result = 6

12

Recursive Programming

b Note that just because we can use recursion to solve aproblem, doesn't mean we should

b For instance, we usually would not use recursion to solvethe sum of 1 to N problem, because the iterative version iseasier to understand

b However, for some problems, recursion provides an elegantsolution, often cleaner than an iterative version

b You must carefully decide whether recursion is the correcttechnique for any problem

Page 199: Presentation slides for Java Software Solutionsmtrutsch/teaching/class/90301/HandoutAllSlides...Presentation slides for Java Software Solutions ... Presentation slides for Java Software

7

13

Indirect Recursion

b A method invoking itself is considered to be direct recursion

b A method could invoke another method, which invokesanother, etc., until eventually the original method isinvoked again

b For example, method m1 could invoke m2, which invokesm3, which in turn invokes m1 again

b This is called indirect recursion, and requires all the samecare as direct recursion

b It is often more difficult to trace and debug

14

Indirect Recursion

m1 m2 m3

m1 m2 m3

m1 m2 m3

Page 200: Presentation slides for Java Software Solutionsmtrutsch/teaching/class/90301/HandoutAllSlides...Presentation slides for Java Software Solutions ... Presentation slides for Java Software

8

Maze Traversal

b We can use recursion to find a path through a maze

b From each location, we can search in each direction

b Recursion keeps track of the path through the maze

b The base case is an invalid move or reaching the finaldestination

b See MazeSearch.java (page 472)

b See Maze.java (page 474)

Towers of Hanoi

b The Towers of Hanoi is a puzzle made up of three verticalpegs and several disks that slide on the pegs

b The disks are of varying size, initially placed on one pegwith the largest disk on the bottom with increasinglysmaller ones on top

b The goal is to move all of the disks from one peg to anotherunder the following rules:• We can move only one disk at a time

• We cannot move a larger disk on top of a smaller one

Page 201: Presentation slides for Java Software Solutionsmtrutsch/teaching/class/90301/HandoutAllSlides...Presentation slides for Java Software Solutions ... Presentation slides for Java Software

9

Towers of Hanoi

b An iterative solution to the Towers of Hanoi is quitecomplex

b A recursive solution is much shorter and more elegant

b See SolveTowers.java (page 479)

b See TowersOfHanoi.java (page 480)

18

Mirrored Pictures

b Consider the task of repeatedly displaying a set of images ina mosaic that is reminiscent of looking in two mirrorsreflecting each other

b The base case is reached when the area for the imagesshrinks to a certain size

b See MirroredPictures.java (page 483)

Page 202: Presentation slides for Java Software Solutionsmtrutsch/teaching/class/90301/HandoutAllSlides...Presentation slides for Java Software Solutions ... Presentation slides for Java Software

10

Fractals

b A fractal is a geometric shape made up of the same patternrepeated in different sizes and orientations

b The Koch Snowflake is a particular fractal that begins withan equilateral triangle

b To get a higher order of the fractal, the sides of the triangleare replaced with angled line segments

b See KochSnowflake.java (page 486)

b See KochPanel.java (page 489)

Page 203: Presentation slides for Java Software Solutionsmtrutsch/teaching/class/90301/HandoutAllSlides...Presentation slides for Java Software Solutions ... Presentation slides for Java Software

1

Chapter 12: Data Structures

Presentation slides for

Java Software SolutionsFoundations of Program Design

Second Edition

by John Lewis and William Loftus

Java Software Solutions is published by Addison-Wesley

Presentation slides are copyright 2000 by John Lewis and William Loftus. All rights reserved.Instructors using the textbook may use and modify these slides for pedagogical purposes.

2

Data Structures

b We can now explore some advanced techniques fororganizing and managing information

b Chapter 12 focuses on:• dynamic structures

• Abstract Data Types (ADTs)

• linked lists

• queues

• stacks

Page 204: Presentation slides for Java Software Solutionsmtrutsch/teaching/class/90301/HandoutAllSlides...Presentation slides for Java Software Solutions ... Presentation slides for Java Software

2

3

Static vs. Dynamic Structures

b A static data structure has a fixed size

b This meaning is different than those associated with thestatic modifier

b Arrays are static; once you define the number of elementsit can hold, it doesn’t change

b A dynamic data structure grows and shrinks as required bythe information it contains

4

Object References

b Recall that an object reference is a variable that stores theaddress of an object

b A reference can also be called a pointer

b They are often depicted graphically:

studentJohn Smith

407253.57

Page 205: Presentation slides for Java Software Solutionsmtrutsch/teaching/class/90301/HandoutAllSlides...Presentation slides for Java Software Solutions ... Presentation slides for Java Software

3

5

References as Links

b Object references can be used to create links betweenobjects

b Suppose a Student class contained a reference to anotherStudent object

John Smith407253.57

Jane Jones588213.72

6

References as Links

b References can be used to create a variety of linkedstructures, such as a linked list:

studentList

Page 206: Presentation slides for Java Software Solutionsmtrutsch/teaching/class/90301/HandoutAllSlides...Presentation slides for Java Software Solutions ... Presentation slides for Java Software

4

7

Abstract Data Types

b An abstract data type (ADT) is an organized collection ofinformation and a set of operations used to manage thatinformation

b The set of operations define the interface to the ADT

b As long as the ADT accurately fulfills the promises of theinterface, it doesn't really matter how the ADT isimplemented

b Objects are a perfect programming mechanism to createADTs because their internal details are encapsulated

8

Abstraction

b Our data structures should be abstractions

b That is, they should hide details as appropriate

b We want to separate the interface of the structure from itsunderlying implementation

b This helps manage complexity and makes the structuresmore useful

Page 207: Presentation slides for Java Software Solutionsmtrutsch/teaching/class/90301/HandoutAllSlides...Presentation slides for Java Software Solutions ... Presentation slides for Java Software

5

9

Intermediate Nodes

b The objects being stored should not have to deal with thedetails of the data structure in which they may be stored

b For example, the Student class stored a link to the nextStudent object in the list

b Instead, we can use a separate node class that holds areference to the stored object and a link to the next node inthe list

b Therefore the internal representation actually becomes alinked list of nodes

Book Collection

b Let’s explore an example of a collection of Book objects

b The collection is managed by the BookList class, whichhas an private inner class called BookNode

b Because the BookNode is private to BookList, theBookList methods can directly access BookNode datawithout violating encapsulation

b See Library.java (page 500)

b See BookList.java (page 501)

b See Book.java (page 503)

Page 208: Presentation slides for Java Software Solutionsmtrutsch/teaching/class/90301/HandoutAllSlides...Presentation slides for Java Software Solutions ... Presentation slides for Java Software

6

11

Other Dynamic List Implementations

b It may be convenient to implement as list as a doubly linkedlist, with next and previous references:

list

12

Other Dynamic List Implementations

b It may also be convenient to use a separate header node,with references to both the front and rear of the list

count: 4frontrear

list

Page 209: Presentation slides for Java Software Solutionsmtrutsch/teaching/class/90301/HandoutAllSlides...Presentation slides for Java Software Solutions ... Presentation slides for Java Software

7

13

Queues

b A queue is similar to a list but adds items only to the end ofthe list and removes them from the front

b It is called a FIFO data structure: First-In, First-Out

b Analogy: a line of people at a bank teller’s window

enqueue dequeue

14

Queues

b We can define the operations on a queue as follows:• enqueue - add an item to the rear of the queue

• dequeue - remove an item from the front of the queue

• empty - returns true if the queue is empty

b As with our linked list example, by storing generic Objectreferences, any object can be stored in the queue

b Queues are often helpful in simulations and any processingin which items get “backed up”

Page 210: Presentation slides for Java Software Solutionsmtrutsch/teaching/class/90301/HandoutAllSlides...Presentation slides for Java Software Solutions ... Presentation slides for Java Software

8

15

Stacks

b A stack ADT is also linear, like a list or queue

b Items are added and removed from only one end of a stack

b It is therefore LIFO: Last-In, First-Out

b Analogy: a stack of plates

16

Stacks

b Stacks are often drawn vertically:

poppush

Page 211: Presentation slides for Java Software Solutionsmtrutsch/teaching/class/90301/HandoutAllSlides...Presentation slides for Java Software Solutions ... Presentation slides for Java Software

9

17

Stacks

b Some stack operations:• push - add an item to the top of the stack

• pop - remove an item from the top of the stack

• peek - retrieves the top item without removing it

• empty - returns true if the stack is empty

b The java.util package contains a Stack class, which isimplemented using a Vector

b See Decode.java (page 508)

Collection Classes

b The Java 2 platform contains a Collections API

b This group of classes represent various data structures usedto store and manage objects

b Their underlying implementation is implied in the classnames, such as ArrayList and LinkedList

b Several interfaces are used to define operations on thecollections, such as List, Set, SortedSet, Map, andSortedMap

Page 212: Presentation slides for Java Software Solutionsmtrutsch/teaching/class/90301/HandoutAllSlides...Presentation slides for Java Software Solutions ... Presentation slides for Java Software