Download presentation
Presentation is loading. Please wait.
1
CSI 1102 Introduction to Software Design
Prof. Dr.-Ing. Abdulmotaleb El Saddik University of Ottawa (SITE 5-037) (613) x 6277 site.uottawa.ca mcrlab.uottawa.ca
2
Learning objectives Brief review of the basic computer processing concepts Understand what problem solving entails Understand why problem solving skills are so important Describe the various levels of programming languages Understand a first Java program and its basic structure Source: Sections , Chapter 1 (L&L)
3
A brief review of Networking
Read through Sections to ensure you are “up to date”
4
PC Penetration Worldwide
Sources: IDC, UN
5
Hardware and Software Hardware
the physical, tangible parts of a computer keyboard, monitor, disks, wires, chips, etc. Software programs and data a program is a series of instructions A computer requires both hardware and software Each is essentially useless without the other
6
Software Categories Operating System controls all machine activities
provides the user interface to the computer manages resources such as the CPU and memory Windows XP, Windows 2000, Unix, Linux, Mac OS Application program generic term for any other kind of software word processors, missile control systems, games Most operating systems and application programs have a graphical user interface (GUI)
7
Networks A network is two or more computers that are connected so that data and resources can be shared Most computers are connected to some kind of network Each computer has its own network address, which uniquely identifies it among the others A file server is a network computer dedicated to storing programs and data that are shared among network users
8
Network Connections Each computer in a network could be directly connected to every other computer in the network These are called point-to-point connections Adding a computer requires a new communication line for each computer already in the network This technique is not practical for more than a few close machines
9
Network Connections Most networks share a single communication line
Adding a new computer to the network is relatively easy Network traffic must take turns using the line, which introduces delays Often information is broken down in parts, called packets, which are sent to the receiving machine and then reassembled
10
Local-Area Networks A Local-Area Network (LAN) covers a small
distance and a small number of computers A LAN often connects the machines in a single room or building
11
Wide-Area Networks A Wide-Area Network (WAN)
LAN A Wide-Area Network (WAN) connects two or more LANs, often over long distances LAN A LAN usually is owned by one organization, but a WAN often connects groups in different countries
12
The Internet The Internet is a WAN which spans the entire planet
The word Internet comes from the term internetworking, which implies communication among networks It started as a United States government project, sponsored by the Advanced Research Projects Agency (ARPA) - originally it was called the ARPANET The Internet grew quickly throughout the 1980s and 90s Less than 600 computers were connected to the Internet in 1983; by the year 2000 there were over 10 million
13
The World Wide Web The World Wide Web is just ONE application of the Internet allows many different types of information to be accessed using a common interface A browser is a program which accesses and presents information text, graphics, video, sound, audio, executable programs A Web document usually contains links to other Web documents, creating a hypermedia environment The term Web comes from the fact that information is not organized in a linear fashion Other Internet applications: , Telnet, FTP, etc…
14
The World Wide Web Web documents are often defined using the HyperText Markup Language (HTML) Information on the Web is found using a Uniform Resource Locator (URL): ftp://java.sun.com/applets/animation.zip A URL indicates a protocol (http), a domain, and possibly specific documents
15
People on the Internet (Worldwide)
Source: IDC
17
Programming & Programming Languages
Source: Sections , Chapter 1 (L&L)
18
So what is Problem Solving?
The purpose of writing a program is to solve a problem 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
19
Problem Solving: “Divide and Conquer”
Many software projects fail because the developer didn't really understand the problem to be solved We must avoid assumptions and clarify ambiguities As problems and their solutions become larger, we must organize our development into manageable pieces: “Divide and Conquer” This technique is fundamental to software development
20
Object-oriented approach to Problem Solving
We will dissect our solutions into pieces called classes and objects, taking an object-oriented approach “If you want to eat an elephant, take one bite at a time”.
21
Problem solving through a programming language
So suppose we have a problem to be solved We choose to design and implement a computer program to solve the problem We use a programming language to do the job for us A programming language specifies the words and symbols that we can use to write a program employs a set of rules that dictate how the words and symbols can be put together to form valid program statements Examples of programming languages: Fortran, Cobol, C++, C, Delphi, Pascal, Smalltalk and JAVA
22
Different Programming Language Levels
There are four programming language levels: machine language assembly language high-level language fourth-generation language Each type of CPU has its own specific machine language The other levels were created to make it easier for a human being to read and write programs
23
Basic Program Development
Edit and save program errors errors Compile program Execute program and evaluate results
24
Problem solving using JAVA
The Java programming language was created by Sun Microsystems, Inc. It was introduced in 1995 and it's popularity has grown quickly since It is an object-oriented language
25
Java Program Structure
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 These terms will be explored in detail throughout the course, starting from next week A Java application always contains a method called main See Lincoln.java (page 30)
26
Java Program Structure
// comments about the class public class MyProgram { } class header class body Comments can be added almost anywhere
27
Java Program Structure
// comments about the class public class MyProgram { } // comments about the method public static void main (String[] args) { } method header method body
28
Lincoln.java //************************************************************** // Lincoln.java Author: Lewis and Loftus // // Demonstrates the basic structure of a Java application. public class Lincoln { // // Prints a presidential quote. public static void main (String[] args) System.out.println ("A quote by Abraham Lincoln:"); System.out.println ("Whatever you are, be a good one."); }
29
About programming language: They all have the following in common
Basic Components Comments Identifiers (Reserved Words) Symbols (e.g. <, >, =, …) White Spaces Syntax and Semantics Translation Errors
30
What are Comments? Comments in a program are called inline documentation They should be included to explain the purpose of the program and describe processing steps They do not affect how a program works Java comments can take three forms: // this comment runs to the end of the line /* this comment runs to the terminating symbol, even across line breaks */ /** this is a javadoc comment */
31
The Importance of Comments
Describe WHAT, WHY, HOW and by WHOM Very important for further use To understand years from now Developer’s turnover high Do not add them at the end!!!! Without comments is very difficult to maintain code
32
Lincoln.java //*********************************************************** // Lincoln.java Author: Lewis and Loftus // // Demonstrates the basic structure of a Java application. public class Lincoln { // // Prints a presidential quote. public static void main (String[] args) System.out.println ("A quote by Abraham Lincoln:"); System.out.println ("Whatever you are, be a good one."); } Comments
33
Identifiers Identifiers are the words a programmer uses in a program
An identifier can be made up of letters, digits, the underscore character ( _ ), and the dollar sign Identifiers cannot begin with a digit Java is case sensitive - Total, total, and TOTAL are different identifiers By convention, Java programmers use different case styles for different types of identifiers, such as title case for class names - Lincoln upper case for constants - MAXIMUM
34
Identifiers Sometimes we choose identifiers ourselves when writing a program (such as Lincoln) Sometimes we are using another programmer's code, so we use the identifiers that they chose (such as println) Often we use special identifiers called reserved words that already have a predefined meaning in the language A reserved word cannot be used in any other way E.g. IF (temp < 30) THEN
35
Reserved Words The Java reserved words: abstract boolean break byte
case catch char class const continue default do double else extends false final finally float for goto if implements import instanceof int interface long native new null package private protected public return short static strictfp super switch synchronized this throw throws transient true try void volatile while
36
About Syntax and Semantics
The syntax rules of a language define how we can put together symbols, reserved words, and identifiers to make a valid program E.g. if (height > tallest) then { tallest = height; } The semantics of a program statement define what that statement means (its purpose or role in a program) E.g. We want to determine the tallest person.
37
About Syntax and Semantics
A program that is syntactically correct is not necessarily logically (semantically) correct A program will always do what we tell it to do, not what we meant to tell it to do !!! Typical error incorrect boundaries E.g. (height > tallest) instead of (height >= tallest)
38
What are White Spaces? Spaces, blank lines, and tabs are called white space White space is used to separate words and symbols in a program Extra white space is ignored A valid Java program can be formatted in many ways Programs should be formatted to enhance readability, using consistent indentation See Lincoln2.java (page 37) See Lincoln3.java (page 38)
39
A BADLY structured Java example
//*************************************************** // Lincoln2.java Author: Lewis and Loftus // // Demonstrates a poorly formatted, though valid, program. //********************************************************* public class Lincoln2{public static void main(String[]args){ System.out.println("A quote by Abraham Lincoln:"); System.out.println("Whatever you are, be a good one.");}}
40
Lincoln3.java //******************************************************************** // Lincoln3.java Author: Lewis and Loftus // // Demonstrates another valid program that is poorly formatted. public class Lincoln3 { public static void main ( String [] args ) System.out.println ( "A quote by Abraham Lincoln:" ) ; System.out.println "Whatever you are, be a good one." ) ; }
41
Translation of Programming Languages
A program must be translated into machine language before it can be executed on a particular type of CPU This can be accomplished in several ways A compiler is a software tool which translates source code into a specific target language Often, that target language is the machine language for a particular CPU type The Java approach is somewhat different
42
Translation in Java Java source code Java bytecode Java compiler
interpreter Bytecode compiler Machine code
43
Java Compiling: javac <Identifier.java> javac Lincoln.java
You will get: Lincoln.class Executing: java <Identifier> java Lincoln
44
Java Translation The Java compiler translates Java source code into a special representation called bytecode Java bytecode is not the machine language for any traditional CPU Another software tool, called an interpreter, translates bytecode into machine language and executes it Therefore the Java compiler is not tied to any particular machine Java is considered to be architecture-neutral
45
About Errors A program can have three types of errors
The compiler will find syntax errors and other basic problems (compile-time errors) If compile-time errors exist, an executable version of the program is not created A problem can occur during program execution, such as trying to divide by zero, which causes a program to terminate abnormally (run-time errors) A program may run, but produce incorrect results, perhaps using an incorrect formula (logical errors)
46
Creating your program: Java Development Environments
Sun Java Development Kit (JDK) Sun Forte for Java Borland JBuilder MetroWerks CodeWarrior Microsoft Visual J++ Symantec Café Monash BlueJ RealJ ( Used in Lab B02 Though the details of these environments differ, the basic compilation and execution process is essentially the same
47
Introduction to Graphics
The last one or two sections of each chapter of the textbook focus on graphical issues Most computer programs have graphical components A picture or drawing must be digitized for storage on a computer A picture consists of pixels, and each pixel is stored separately
48
Representing Color A black and white picture can be stored using one bit per pixel (0 = white and 1 = black) A colored picture requires more information; there are several techniques for representing colors For example, every color can be represented as a mixture of the three additive primary colors Red, Green, and Blue In Java, each color is represented by three numbers between 0 and 255 that collectively are called an RGB value
49
Coordinate Systems Each pixel can be identified using a two- dimensional coordinate system When referring to a pixel in a Java program, we use a coordinate system with the origin in the top-left corner Y X (0, 0) 112 40 (112, 40)
50
Summary of Lecture Lecture has focused on programming and programming languages Students should now Understand what problem solving entails Understand why problem solving skills are so important Describe the various levels of programming languages Understand a first Java program and its basic structure
52
CSI 1102 Introduction to Software Design
Prof. Dr. Abdulmotaleb El Saddik Multimedia Communications Research Laboratory School of Information Technology and Engineering University of Ottawa Ottawa, Ontario, Canada site.uottawa.ca mcrlab.uottawa.ca
53
Objects and Primitive Data
2nd Week: Now we can explore some more fundamental programming concepts Objects and Primitive Data
54
Learning objectives predefined objects primitive data
the declaration and use of variables expressions and operator precedence creating and using objects class libraries Java applets drawing shapes
55
Introduction to Objects
An object represents something with which we can interact in a program An object provides a collection of services that we can tell it to perform for us The services are defined by methods in a class that defines the object A class represents a concept, and an object represents the embodiment of a class A class can be used to create multiple objects
56
Objects and Classes A class (the concept) An object (the realization)
John’s Bank Account Balance: $5,257 An object (the realization) Bank Account Bill’s Bank Account Balance: $1,245,069 Mary’s Bank Account Balance: $16,833 Multiple objects from the same class
57
Inheritance One class can be used to derive another via inheritance
Classes can be organized into inheritance hierarchies Bank Account Account Charge Account Savings Account Checking Account
58
System.out.println ("Whatever you are, be a good one.");
Using Objects The System.out object represents a destination to which we can send output In the Lincoln program, we invoked the println method of the System.out object: System.out.println ("Whatever you are, be a good one."); method object information provided to the method (parameters)
59
The print Method The System.out object provides another service as well The print method is similar to the println method, except that it does not advance to the next line Therefore anything printed after a print statement will appear on the same line See Countdown.java (page 65)
60
Abstraction An abstraction hides (or suppresses) the right details at the right time An object is abstract in that we don't have to think about its internal details in order to use it For example, we don't have to know how the println method works in order to invoke it A human being can manage only seven (plus or minus 2) pieces of information at one time But if we group information into chunks (such as objects) we can manage many complicated pieces at once Classes and objects help us write complex software
61
Character Strings Every character string is an object in Java, defined by the String class Every string literal, delimited by double quotation marks, represents a String object The string concatenation operator (+) is used to append one string to the end of another It can also be used to append a number to a string A string literal cannot be broken across two lines in a program See Facts.java (page 68)
62
String Concatenation The plus operator (+) is also used for arithmetic addition The function that the + operator performs depends on the type of the information on which it operates If both operands are strings, or if one is a string and one is a number, it performs string concatenation If both operands are numeric, it adds them The + operator is evaluated left to right Parentheses can be used to force the operation order See Addition.java (page 70)
63
Escape Sequences What if we wanted to print a double quote character?
The following line would confuse the compiler because it would interpret the second quote as the end of the string System.out.println ("I said "Hello" to you."); An escape sequence is a series of characters that represents a special character An escape sequence begins with a backslash character (\), which indicates that the character(s) that follow should be treated in a special way System.out.println ("I said \"Hello\" to you.");
64
Escape Sequences Some Java escape sequences: See Roses.java (page 71)
\b \t \n \r \" \' \\ Meaning backspace tab newline carriage return double quote single quote backslash See Roses.java (page 71)
65
Multiple variables can be created in one declaration
A variable is a name for a location in memory A variable must be declared by specifying the variable's name and the type of information that it will hold data type variable name int total; int count, temp, result; Multiple variables can be created in one declaration
66
Variables A variable can be given an initial value in the declaration
int sum = 0; int base = 32, max = 149; When a variable is referenced in a program, its current value is used See PianoKeys.java (page 73)
67
Assignment An assignment statement changes the value of a variable
The assignment operator is the = sign total = 55; The expression on the right is evaluated and the result is stored in the variable on the left The value that was in total is overwritten You can assign only a value to a variable that is consistent with the variable's declared type See Geometry.java (page 74)
68
final int MIN_HEIGHT = 69;
Constants A constant is an identifier that is similar to a variable except that it holds one value while the program is active The compiler will issue an error if you try to change the value of a constant during execution In Java, we use the final modifier to declare a constant final int MIN_HEIGHT = 69; Constants: give names to otherwise unclear literal values facilitate updates of values used throughout a program prevent inadvertent attempts to change a value
69
Primitive Data There are exactly eight primitive data types in Java
Four of them represent integers: byte, short, int, long Two of them represent floating point numbers: float, double One of them represents characters: char And one of them represents boolean values: boolean
70
Numeric Primitive Data
The difference between the various numeric primitive types is their size, and therefore the values they can store: Type byte short int long float double Storage 8 bits 16 bits 32 bits 64 bits Min Value -128 -32,768 -2,147,483,648 < -9 x 1018 +/- 3.4 x 1038 with 7 significant digits +/- 1.7 x with 15 significant digits Max Value 127 32,767 2,147,483,647 > 9 x 1018
71
Characters A char variable stores a single character from the Unicode character set A character set is an ordered list of characters, and each character corresponds to a unique number The Unicode character set uses sixteen bits per character, allowing for 65,536 unique characters It is an international character set, containing symbols and characters from many world languages Character literals are delimited by single quotes: 'a' 'X' '7' '$' ',' '\n'
72
Characters The ASCII character set is older and smaller than Unicode, but is still quite popular The ASCII characters are a subset of the Unicode character set, including: uppercase letters lowercase letters punctuation digits special symbols control characters A, B, C, … a, b, c, … period, semi-colon, … 0, 1, 2, … &, |, \, … carriage return, tab, ...
73
Boolean A boolean value represents a true or false condition
A boolean also can be used to represent any two states, such as a light bulb being on or off The reserved words true and false are the only valid values for a boolean type boolean done = false;
74
Arithmetic Expressions
An expression is a combination of one or more operands and their operators Arithmetic expressions compute numeric results and make use of the arithmetic operators: Addition + Subtraction - Multiplication * Division / Remainder % If either or both operands associated with an arithmetic operator are floating point, the result is a floating point
75
Division and Remainder
If both operands to the division operator (/) are integers, the result is an integer (the fractional part is discarded) 14 / equals? 4 8 / equals? The remainder operator (%) returns the remainder after dividing the second operand into the first 14 % equals? 2 8 % equals? 8
76
result = total + count / max - offset;
Operator Precedence Operators can be combined into complex expressions result = total + count / max - offset; Operators have a well-defined precedence which determines the order in which they are evaluated Multiplication, division, and remainder are evaluated prior to addition, subtraction, and string concatenation Arithmetic operators with the same precedence are evaluated from left to right Parentheses can be used to force the evaluation order
77
Operator Precedence What is the order of evaluation in the following expressions? a + b + c + d + e a + b * c - d / e 1 2 3 4 3 1 4 2 a / (b + c) - d % e 2 1 4 3 a / (b * (c + (d - e))) 4 3 2 1
78
Assignment Revisited The assignment operator has a lower precedence than the arithmetic operators First the expression on the right hand side of the = operator is evaluated answer = sum / 4 + MAX * lowest; 4 1 3 2 Then the result is stored in the variable on the left hand side
79
Assignment Revisited The right and left hand sides of an assignment statement can contain the same variable First, one is added to the original value of count count = count + 1; Then the result is stored back into count (overwriting the original value)
80
Data Conversions Sometimes it is convenient to convert data from one type to another For example, we may want to treat an integer as a floating point value during a computation Conversions must be handled carefully to avoid losing information Widening conversions are safest because they tend to go from a small data type to a larger one (such as a short to an int) Narrowing conversions can lose information because they tend to go from a large data type to a smaller one (such as an int to a short)
81
Data Conversions In Java, data conversions can occur in three ways:
assignment conversion arithmetic promotion casting Assignment conversion occurs when a value of one type is assigned to a variable of another Only widening conversions can happen via assignment Arithmetic promotion happens automatically when operators in expressions convert their operands
82
result = (float) total / count;
Data Conversions Casting is the most powerful, and dangerous, technique for conversion Both widening and narrowing conversions can be accomplished by explicitly casting a value To cast, the type is put in parentheses in front of the value being converted For example, if total and count are integers, but we want a floating point result when dividing them, we can cast total: result = (float) total / count;
83
Creating Objects A variable holds either a primitive type or a reference to an object A class name can be used as a type to declare an object reference variable String title; No object is created with this declaration An object reference variable holds the address of an object The object itself must be created separately
84
Creating Objects Generally, we use the new operator to create an object title = new String ("Java Software Solutions"); This calls the String constructor, which is a special method that sets up the object Creating an object is called instantiation An object is an instance of a particular class
85
title = "Java Software Solutions";
Creating Objects Because strings are so common, we don't have to use the new operator to create a String object title = "Java Software Solutions"; This is special syntax that works only for strings Once an object has been instantiated, we can use the dot operator to invoke its methods title.length()
86
String Methods The String class has several methods that are useful for manipulating strings Many of the methods return a value, such as an integer or a new String object See the list of String methods on page 89 and in Appendix M See StringMutation.java (page 90)
87
Class Libraries A class library is a collection of classes that we can use when developing programs The Java standard class library is part of any Java development environment Its classes are not part of the Java language per se, but we rely on them heavily The System class and the String class are part of the Java standard class library Other class libraries can be obtained through third party vendors, or you can create them yourself
88
Packages The classes of the Java standard class library are organized into packages Some of the packages in the standard class library are: Package java.lang java.applet java.awt javax.swing java.net java.util javax.xml.parsers Purpose General support Creating applets for the web Graphics and graphical user interfaces Additional graphics capabilities and components Network communication Utilities XML document processing
89
The import Declaration
When you want to use a class from a package, you could use its fully qualified name java.util.Random Or you can import the class, and then use just the class name import java.util.Random; To import all classes in a particular package, you can use the * wildcard character import java.util.*;
90
The import Declaration
All classes of the java.lang package are imported automatically into all programs That's why we didn't have to import the System or String classes explicitly in earlier programs The Random class is part of the java.util package It provides methods that generate pseudorandom numbers See RandomNumbers.java (page 97)
91
temp = Math.cos(90) + Math.sqrt(delta);
Class Methods Some methods can be invoked through the class name, instead of through an object of the class These methods are called class methods or static methods The Math class contains many static methods, providing various mathematical functions, such as absolute value, trigonometry functions, square root, etc. temp = Math.cos(90) + Math.sqrt(delta);
92
The Keyboard Class The Keyboard class is NOT part of the Java standard class library It is provided by the authors of the textbook to make reading input from the keyboard easy Details of the Keyboard class are explored in Chapter 5 The Keyboard class is part of a package called cs1 It contains several static methods for reading particular types of data See Echo.java (page 101) See Quadratic.java (page 102)
93
getCurrencyInstance() getPercentInstance()
Formatting Output The NumberFormat class has static methods that return a formatter object getCurrencyInstance() getPercentInstance() Each formatter object has a method called format that returns a string with the specified information in the appropriate format See Price.java (page 104)
94
Formatting Output The DecimalFormat class can be used to format a floating point value in generic ways For example, you can specify that the number should be printed to three decimal places The constructor of the DecimalFormat class takes a string that represents a pattern for the formatted number See CircleStats.java (page 107)
95
Applets A Java application is a stand-alone program with a main method (like the ones we've seen so far) A Java applet is a program that is intended to transported over the Web and executed using a web browser An applet also can be executed using the appletviewer tool of the Java Software Development Kit An applet doesn't have a main method Instead, there are several special methods that serve specific purposes
96
Applets The paint method, for instance, is executed automatically and is used to draw the applet’s contents The paint method accepts a parameter that is an object of the Graphics class A Graphics object defines a graphics context on which we can draw shapes and text The Graphics class has several methods for drawing shapes
97
Applets The class that defines an applet extends the Applet class
This makes use of inheritance, which is explored in more detail in Chapter 7 See Einstein.java (page 109) An applet is embedded into an HTML file using a tag that references the bytecode file of the applet class The bytecode version of the program is transported across the web and executed by a Java interpreter that is part of the browser
98
The HTML applet Tag <html> <head>
<title>The Einstein Applet</title> </head> <body> <applet code="Einstein.class" width=350 height=175> </applet> </body> </html>
99
Drawing Shapes Let's explore some of the methods of the Graphics class that draw shapes in more detail A shape can be filled or unfilled, depending on which method is invoked The method parameters specify coordinates and sizes Recall from Chapter 1 that the Java coordinate system has the origin in the top left corner Shapes with curves, like an oval, are usually drawn by specifying the shape’s bounding rectangle An arc can be thought of as a section of an oval
100
Drawing a Line page.drawLine (10, 20, 150, 45); or
X Y 10 150 20 45 page.drawLine (10, 20, 150, 45); page.drawLine (150, 45, 10, 20); or
101
Drawing a Rectangle X Y 50 20 40 100 page.drawRect (50, 20, 100, 40);
102
Drawing an Oval bounding rectangle page.drawOval (175, 20, 50, 80);
X Y 175 20 80 bounding rectangle 50 page.drawOval (175, 20, 50, 80);
103
The Color Class A color is defined in a Java program using an object created from the Color class The Color class also contains several static predefined colors, including: Object Color.black Color.blue Color.cyan Color.orange Color.white Color.yellow RGB Value 0, 0, 0 0, 0, 255 0, 255, 255 255, 200, 0 255, 255, 255 255, 255, 0
104
The Color Class Every drawing surface has a background color
Every graphics context has a current foreground color Both can be set explicitly See Snowman.java (page115)
105
Summary Chapter 2 has focused on: predefined objects primitive data
the declaration and use of variables expressions and operator precedence creating and using objects class libraries Java applets drawing shapes
106
CSI 1102 Introduction to Software Design
Prof. Dr.-Ing. Abdulmotaleb El Saddik University of Ottawa (SITE 5-037) (613) x 6277 site.uottawa.ca mcrlab.uottawa.ca
107
Program Statements Now we will examine some other program statements
Chapter 3 focuses on: program development stages the flow of control through a method decision-making statements expressions for making complex decisions repetition statements drawing with conditionals and loops
108
Program Development The creation of software involves four basic activities: establishing the requirements creating a design implementing the code testing the implementation The development process is much more involved than this, but these are the four basic development activities
109
Requirements Software requirements specify the tasks a program must accomplish what to do, not how to do it They often include a description of the user interface An initial set of requirements often are provided, but usually must be critiqued, modified, and expanded Often it is difficult to establish detailed, unambiguous, complete requirements Careful attention to the requirements can save significant time and expense in the overall project
110
Design A software design specifies how a program will accomplish its requirements A design includes one or more algorithms to accomplish its goal An algorithm is a step-by-step process for solving a problem An algorithm may be expressed in pseudocode, which is code-like, but does not necessarily follow any specific syntax In object-oriented development, the design establishes the classes, objects, methods, and data that are required
111
Implementation Implementation is the process of translating a design into source code Most novice programmers think that writing code is the heart of software development, but actually it should be the least creative step Almost all important decisions are made during requirements and design stages Implementation should focus on: Coding details, including style guidelines and documentation
112
Testing A program should be executed multiple times with various input in an attempt to find errors Debugging is the process of discovering the causes of problems and fixing them Programmers often think erroneously that there is "only one more bug" to fix Tests should consider design details as well as overall requirements
113
Flow of Control Unless specified otherwise, the order of statement execution through a method is linear: one statement after the other in sequence Some programming statements modify that order, allowing us to: decide whether or not to execute a particular statement, or perform a statement over and over, repetitively Loop 3 kinds of Loops WHILE, DO, and FOR These decisions are based on a boolean expression (also called a condition) that evaluates to true or false The order of statement execution is called the flow of control
114
Conditional Statements
A conditional statement lets us choose which statement will be executed next Therefore they are sometimes called selection statements Conditional statements give us the power to make basic decisions Java's conditional statements are the if statement the if-else statement the switch statement
115
The if Statement The if statement has the following syntax:
The condition must be a boolean expression. It must evaluate to either true or false. if is a Java reserved word if ( condition ) statement; If the condition is true, the statement is executed. If it is false, the statement is skipped.
116
The if Statement 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 sum is either greater than the value of MAX, or it is not. If the condition is true, the assignment statement is executed. If it is not, the assignment statement is skipped. Either way, the call to println is executed next. See Age.java (page 135)
117
Logic of an if statement
condition evaluated false statement true
118
Boolean Expressions A condition often uses one of Java's equality operators or relational 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 Note the difference between the equality operator (==) and the assignment operator (=)
119
The if-else Statement An else clause can be added to an if statement to make an if-else statement if ( condition ) statement1; else statement2; If the condition is true, statement1 is executed; if the condition is false, statement2 is executed One or the other will be executed, but not both See Wages.java (page 139)
120
Logic of an if-else statement
condition evaluated false statement2 statement1 true
121
Block Statements Several statements can be grouped together into a block statement A block is delimited by braces : { … } A block statement can be used wherever a statement is called for by the Java syntax For example, in an if-else statement, the if portion, or the else portion, or both, could be block statements See Guessing.java (page 141)
122
Example import cs1.Keyboard; import java.util.Random;
public class Guessing { public static void main (String[] args) final int MAX = 10; int answer, guess; Random generator = new Random(); answer = generator.nextInt(MAX) + 1; System.out.print ("I'm thinking of a number between 1 and " + MAX + ". Guess what it is: "); guess = Keyboard.readInt(); if (guess == answer) System.out.println ("You got it! Good guessing!"); else System.out.println ("That is not correct, sorry."); System.out.println ("The number was " + answer); }
123
Nested if Statements The statement executed as a result of an if statement or else clause could be another if statement These are called nested if statements See MinOfThree.java (page 143) An else clause is matched to the last unmatched if (no matter what the indentation implies) Braces can be used to specify the if statement to which an else clause belongs
124
Example import cs1.Keyboard; public class MinOfThree {
public static void main (String[] args) int num1, num2, num3, min = 0; System.out.println ("Enter three integers: "); num1 = Keyboard.readInt(); num2 = Keyboard.readInt(); num3 = Keyboard.readInt(); if (num1 < num2) if (num1 < num3) min = num1; else min = num3; if (num2 < num3) min = num2; System.out.println ("Minimum value: " + min); }
125
The switch Statement The switch statement provides another means to decide which statement to execute next The switch statement evaluates an expression, then attempts to match the result to one of several possible cases Each case contains a value and a list of statements The flow of control transfers to statement associated with the first value that matches
126
The switch Statement The general syntax of a switch statement is:
switch ( expression ) { case value1 : statement-list1 case value2 : statement-list2 case value3 : statement-list3 case ... } switch and case are reserved words If expression matches value2, control jumps to here
127
The switch Statement Often a break statement is used as the last statement in each case's statement list A break statement causes control to transfer to the end of the switch statement If a break statement is not used, the flow of control will continue into the next case Sometimes this can be appropriate, but usually we want to execute only the statements associated with one case
128
The switch Statement A switch statement can have an optional default case The default case has no associated value and simply uses the reserved word default If the default case is present, control will transfer to it if no other case value matches Though the default case can be positioned anywhere in the switch, usually it is placed at the end If there is no default case, and no other value matches, control falls through to the statement after the switch
129
The switch Statement The expression of a switch statement must result in an integral type, meaning an int or a char It cannot be a boolean value, a floating point value (float or double), a byte, a short, or a long The implicit boolean condition in a switch statement is equality - it tries to match the expression with a value You cannot perform relational checks with a switch statement See GradeReport.java (page 147)
130
Example switch (category) { case 8:
System.out.println ("above average. Nice job."); break; case 7: System.out.println ("average."); case 6: System.out.println ("below average. You should see the"); System.out.println ("instructor to clarify the material " + "presented in class."); default: System.out.println ("not passing."); }
131
Today's Killer Application
Internet Access
132
Logical Operators Boolean expressions can use the following logical operators: ! Logical NOT && Logical AND || Logical OR They all take boolean operands and produce boolean results Logical NOT is a unary operator (it operates on one operand Logical AND and logical OR are binary operators (each operates on two operands)
133
Logical NOT The logical NOT operation is also called logical negation or logical complement If some boolean condition a is true, then !a is false; if a is false, then !a is true Logical expressions can be shown using truth tables a !a true false
134
Logical AND and Logical OR
The logical AND expression a && b is true if both a and b are true, and false otherwise The logical OR expression a || b is true if a or b or both are true, and false otherwise
135
Truth Tables A truth table shows the possible true/false combinations of the terms Since && and || each have two operands, there are four possible combinations of conditions a and b a b a && b a || b true false
136
Logical Operators Conditions can use logical operators to form complex expressions if (total < MAX+5 && !found) System.out.println ("Processing…"); Logical operators have precedence relationships among themselves and with other operators all logical operators have lower precedence than the relational or arithmetic operators logical NOT has higher precedence than logical AND and logical OR
137
Operator precedence This is not a complete list, but shows the operators we have seen so far: Highest: ! Next: unary minus (represent a negative number) Next: new (cast) Next: * / % Next: Next: < > <= >= Next: == != Lowest: = All operators on the same line have equal precedence, and are evaluated from left to right in the order they appear in an expression.
138
Short Circuited Operators
The processing of logical AND and logical OR is “short-circuited” If the left operand is sufficient to determine the result, the right operand is not evaluated if (count != 0 && total/count > MAX) System.out.println ("Testing…"); This type of processing must be used carefully
139
Truth Tables Specific expressions can be evaluated using truth tables
total < MAX found !found total < MAX && !found false true total < MAX found !found total < MAX || !found false true
140
Comparing Characters We can use the relational operators on character data The results are based on the Unicode character set The following condition is true because the character + comes before the character J in the Unicode character set: if ('+' < 'J') System.out.println ("+ is less than J"); The uppercase alphabet (A-Z) followed by the lowercase alphabet (a-z) appear in alphabetical order in the Unicode character set
141
Comparing Strings Remember that a character string in Java is an object We cannot use the relational operators to compare strings The equals method can be called with strings to determine if two strings contain exactly the same characters in the same order The String class also contains a method called compareTo to determine if one string comes before another (based on the Unicode character set)
142
Lexicographic Ordering
Because comparing characters and strings is based on a character set, it is called a lexicographic ordering This is not strictly alphabetical when uppercase and lowercase characters are mixed For example, the string "Great" comes before the string "fantastic" because all of the uppercase letters come before all of the lowercase letters in Unicode Also, short strings come before longer strings with the same prefix (lexicographically) Therefore "book" comes before "bookcase"
143
Comparing Float Values
We also have to be careful when comparing two floating point values (float or double) for equality You should rarely use the equality operator (==) when comparing two floats In many situations, you might consider two floating point numbers to be "close enough" even if they aren't exactly equal Therefore, to determine the equality of two floats, you may want to use the following technique: if (Math.abs(f1 - f2) < ) System.out.println ("Essentially equal.");
145
Organization Please refer to the outline for the Assignments:
The following can be found: Lab Assignment 1: Programming projects 1.1 – 1.4 which means (1.1, 1.2, 1.3, 1.4) pp ; Programming projects 2.2, 2.5 pp.123 Practice and Complete in Lab
146
count++; is functionally equivalent to
More Operators To round out our knowledge of Java operators, let's examine a few more In particular, we will examine the increment (++) and decrement (--) operators the assignment (+=) operators the conditional (?) operator The increment and decrement operators are arithmetic and operate on one operand count++; is functionally equivalent to count = count + 1;
147
Increment and Decrement
The increment and decrement operators can be applied in prefix form (before the operand) or postfix form (after the operand) When used alone in a statement, the prefix and postfix forms are functionally equivalent. That is, count++; is equivalent to ++count;
148
Increment and Decrement
When used in a larger expression, the prefix and postfix forms have different effects In both cases the variable is incremented (decremented) But the value used in the larger expression depends on the form used: Expression count++ ++count count-- --count Operation add 1 subtract 1 Value Used in Expression old value new value
149
Increment and Decrement
If count currently contains 45, then the statement total = count++; assigns 45 to total and 46 to count If count currently contains 45, then the statement total = ++count; assigns the value 46 to both total and count
150
Assignment Operators Often we perform an operation on a variable, and then store the result back into that variable Java provides assignment operators to simplify that process For example, the statement num += count; is equivalent to num = num + count;
151
Assignment Operators There are many assignment operators, including the following: Operator += -= *= /= %= Example x += y x -= y x *= y x /= y x %= y Equivalent To x = x + y x = x - y x = x * y x = x / y x = x % y
152
Assignment Operators The right hand side of an assignment operator can be a complex expression The entire right-hand expression is evaluated first, then the result is combined with the original variable Therefore result /= (total-MIN) % num; is equivalent to result = result / ((total-MIN) % num);
153
Assignment Operators The behavior of some assignment operators depends on the types of the operands If the operands to the += operator are strings, the assignment operator performs string concatenation The behavior of an assignment operator (+=) is always consistent with the behavior of the "regular" operator (+) I do not recommend using this “shorthand” It can lead to errors. Rather type the complete expression, except in Loops.
154
The Conditional Operator
Java has a conditional operator that evaluates a boolean condition that determines which of two other expressions is evaluated The result of the chosen expression is the result of the entire conditional operator Its syntax is: condition ? expression1 : expression2 If the condition is true, expression1 is evaluated; if it is false, expression2 is evaluated
155
The Conditional Operator
The conditional operator is similar to an if-else statement, except that it forms an expression that returns a value For example: larger = ((num1 > num2) ? num1 : num2); If num1 is greater that num2 , then num1 is assigned to larger; otherwise, num2 is assigned to larger The conditional operator is ternary because it requires three operands
156
The Conditional Operator
Another example: System.out.println ("Your change is " + count + ((count == 1) ? "Dime" : "Dimes")); If count equals 1, then "Dime" is printed If count is anything other than 1, then "Dimes" is printed
157
Repetition Statements
Repetition statements allow us to execute a statement multiple times Often they are referred to as loops Like conditional statements, they are controlled by boolean expressions Java has three kinds of repetition statements: the while loop the do loop the for loop The programmer should choose the right kind of loop for the situation
158
The while Statement The while statement has the following syntax:
while ( condition ) statement; while is a reserved word If the condition is true, the statement is executed. Then the condition is evaluated again. The statement is executed repeatedly until the condition becomes false.
159
Logic of a while Loop condition evaluated false statement true
160
The while Statement Note that if the condition of a while statement is false initially, the statement is never executed Therefore, the body of a while loop will execute zero or more times
161
The While Statement: Average.java
import java.text.DecimalFormat; import cs1.Keyboard; public class Average { // Computes the average of a set of values public static void main (String[] args) { int sum = 0, value, count = 0; double average; DecimalFormat fmt = new DecimalFormat("0.###"); System.out.print("Enter an integer (0 to quit) "); value = Keyboard.readInt(); Continued…
162
The While Statement: Average.java (cont)
while (value != 0) // sentinal 0 terminates the loop { count++; sum += value; System.out.println("The sum so far is " + sum); System.out.print("Enter an integer (0 to quit) "); value = Keyboard.readInt(); } System.out.println("Number of values entered: " + count); average = (double) sum/count; System.out.println("Average number entered: " + average); } }
163
Avoiding Infinite Loops
The body of a while loop eventually must make the condition false If not, it is an infinite loop, which will execute until the user interrupts the program This is a common logical error You should always double check to ensure that your loops will terminate normally
164
Avoiding infinite loops: Forever.java
public class Forever { // Computes the average of a set of values public static void main (String[] args) { int count = 1; while (count <= 25) { System.out.println(count); count--; } System.out.println("Done"); } }
165
Nested Loops Similar to nested if statements, loops can be nested as well That is, the body of a loop can contain another loop Each time through the outer loop, the inner loop goes through its full set of iterations See PalindromeTester.java (page 167)
166
The do Statement The do statement has the following syntax: do {
} while ( condition ) do and while are reserved words The statement is executed once initially, and then the condition is evaluated The statement is executed repeatedly until the condition becomes false
167
Logic of a do Loop statement true condition evaluated false
168
Comparing while and do A do loop is similar to a while loop, except that the condition is evaluated after the body of the loop is executed Therefore the body of a do loop will execute at least once statement true condition evaluated false while loop true condition evaluated statement false do loop
169
The do Statement What is printed if count = 0 and LIMIT =5?
do while (count < LIMIT) { { count = count + 1; count = count + 1; system.out.println(count); system.out.println(count); } } while (count < LIMIT);
170
The for Statement The for statement has the following syntax:
The initialization is executed once before the loop begins The statement is executed until the condition becomes false Reserved word for ( initialization ; condition ; increment ) statement; The increment portion is executed at the end of each iteration The condition-statement-increment cycle is executed repeatedly
171
The for Statement A for loop is functionally equivalent to the
true condition evaluated false increment initialization A for loop is functionally equivalent to the following while loop structure: Like a while loop, the condition of a for statement is tested prior to executing the loop body Therefore, the body of a for loop will execute zero or more times initialization; while ( condition ) { statement; increment; }
172
The for Statement 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, and therefore creates an infinite loop If the increment is left out, no increment operation is performed Both semi-colons are always required in the for loop header
173
The for Statement: Stars.java
public class Stars { // Print lines of stars, from 1 to 10 public static void main (String[] args) { final int MAXROWS = 10; for (int row = 1; row <= MAXROWS; row++) { for (int star = 1; star <= row; star++) System.out.print(‘*’); System.out.println(); } } }
174
Choosing a Loop Structure
When you can’t determine how many times you want to execute the loop body, use a while statement or a do statement If it might be zero or more times, use a while statement If it will be at least once, use a do statement If you can determine how many times you want to execute the loop body, use a for statement
175
Program Development We now have several additional statements and operators at our disposal Following proper development steps is important Suppose you were given some initial requirements: accept a series of test scores compute the average test score determine the highest and lowest test scores display the average, highest, and lowest test scores
176
Program Development: Requirements Analysis
Clarify and flesh out specific requirements How much data will there be? How should data be accepted? Is there a specific output format required? After conferring with the client, we determine: the program must process an arbitrary number of test scores the program should accept input interactively the average should be presented to two decimal places The process of requirements analysis may take a long time
177
Program Development: Design
Determine a possible general solution Input strategy? (Sentinel value?) Calculations needed? An initial algorithm might be expressed in pseudocode Multiple versions of the solution might be needed to refine it Alternatives to the solution should be carefully considered
178
Program Development: Implementation
Translate the design into source code Make sure to follow coding and style guidelines Implementation should be integrated with compiling and testing your solution This process mirrors a more complex development model we'll eventually need to develop more complex software The result is a final implementation See ExamScores.java (page 186)
179
Program Development: Testing
Attempt to find errors that may exist in your programmed solution Compare your code to the design and resolve any discrepancies Determine test cases that will stress the limits and boundaries of your solution Carefully retest after finding and fixing an error
180
More Drawing Techniques
Conditionals and loops can greatly enhance our ability to control graphics See Bullseye.java (page 189) See Boxes.java (page 191) See BarHeights.java (page 193)
181
Summary Chapter 3 has focused on:
Understand the important program development stages Understand the concepts of “flow of control” through a method Selection statements: if, if-else and switch Understand how to use Operators Boolean operators: AND, OR, NOT Other Java operators: increment ++, decrement --, assignment += and conditional ? Repetition statements: while, do and for
182
CSI 1102 Introduction to Software Design
Prof. Dr.-Ing. Abdulmotaleb El Saddik University of Ottawa (SITE 5-037) (613) x 6277 site.uottawa.ca mcrlab.uottawa.ca
183
Writing Classes We've been using predefined classes. Now we will learn to write our own classes to define objects Chapter 4 focuses on: class definitions encapsulation and Java modifiers method declaration, invocation, and parameter passing method overloading method decomposition graphics-based objects
184
Objects An object has: state - descriptive characteristics
behaviors - what it can do (or what can be done to it) For example, consider a coin that can be flipped so that it's face shows either "heads" or "tails" The state of the coin is its current face (heads or tails) The behavior of the coin is that it can be flipped Note that the behavior of the coin might change its state
185
Classes A class is a blueprint of an object
It is the model or pattern from which objects are created For example, the String class is used to define String objects Each String object contains specific characters (its state) Each String object can perform services (behaviors) such as toUpperCase
186
Classes The String class was provided for us by the Java standard class library But we can also write our own classes that define specific objects that we need For example, suppose we want to write a program that simulates the flipping of a coin We can write a Coin class to represent a coin object
187
Classes A class contains data declarations and method declarations
int x, y; char ch; Data declarations Method declarations
188
The Coin Class 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 two possible states We might also define the following methods: a Coin constructor, to initialize the object a flip method, to flip the coin a isHeads method, to determine if the current face is heads a toString method, to return a string description for printing
189
Coin.java public class Coin { public final int HEADS = 0;
public final int TAILS = 1; private int face; public Coin () flip(); } public void flip () face=(int)(Math.random()*2); public int getFace () { return face; } public String toString() String faceName; if (face == HEADS) faceName = "Heads"; else faceName = "Tails"; return faceName;
190
CoinFlips.java import Coin; public class CountFlips {
public static void main (String[] args) final int NUM_FLIPS = 1000; int heads = 0, tails = 0; Coin myCoin = new Coin(); // instantiate the Coin object for (int count=1; count <= NUM_FLIPS; count++) myCoin.flip(); if (myCoin.getFace() == myCoin.HEADS) heads++; else tails++; } System.out.println ("The number flips: " + NUM_FLIPS); System.out.println ("The number of heads: " + heads); System.out.println ("The number of tails: " + tails);
191
The Coin / CountFlips Class revised
See CountFlips.java (page 213) See Coin.java (page 214) Note that the CountFlips program did not use the toString method A program will not necessarily use every service provided by an object Once the Coin class has been defined, we can use it again in other programs as needed
192
Data Scope The scope of data is the area in a program in which that data can be used (referenced) Data declared at the class level can be used by all methods in that class Data declared at the class level is called global data Data declared within a method can be used only in that method Data declared within a method is called local data
193
Instance Data The face variable in the Coin class is called instance data because each instance (object) of the Coin class has its own A class declares the type of the data, but it does not reserve any memory space for it Every time a Coin object is created, a new face variable is created as well The objects of a class share the method definitions, but each has its own data space That's the only way two objects can have different states
194
Instance Data See FlipRace.java (page 217) coin1 class Coin coin2 face
int face; coin2 face 1
195
UML Diagrams UML stands for the Unified Modeling Language
UML diagrams show relationships among classes and objects A UML class diagram consists of one or more classes, each with sections for the class name, attributes, and methods Lines between classes represent associations Associations can show multiplicity
196
UML Class Diagrams A UML class diagram for the FlipRace program:
main (args : String[]) : void Coin face : int flip() : void isHeads() : boolean toString() : String 1 2
197
UML Diagrams A UML object diagram consists of one or more instantiated objects. It is a snapshot of the objects during an executing program, showing data values coin1 : Coin face = 0 coin2 : Coin face = 1
198
Encapsulation We can take one of two views of an object:
internal - the variables the object holds and the methods that make the object useful external - the services that an object provides and how the object interacts From the external view, an object is an encapsulated entity providing a set of specific services These services define the interface to the object Recall from Chapter 2 that an object is an abstraction, hiding details from the rest of the system
199
Encapsulation An object should be self-governing
Any changes to the object's state (its variables) should be made only by that object's methods We should make it difficult, if not impossible, to access an object’s variables other than via its methods The user, or client, of an object can request its services, but it should not have to be aware of how those services are accomplished
200
Encapsulation An encapsulated object can be thought of as a black box
Its inner workings are hidden to the client, which invokes only the interface methods Methods Client Data
201
Visibility Modifiers In Java, we accomplish encapsulation through the appropriate use of visibility modifiers A modifier is a Java reserved word that specifies particular characteristics of a method or data value We've used the modifier final to define a constant Java has three visibility modifiers: public, protected, and private The protected modifier involves inheritance, which we will discuss later
202
Visibility Modifiers Members of a class that are declared with public visibility can be accessed from anywhere Public variables violate encapsulation Members of a class that are declared with private visibility can only be accessed from inside the class Members declared without a visibility modifier have default visibility and can be accessed by any class in the same package Java modifiers are discussed in detail in Appendix F
203
Visibility Modifiers Methods that provide the object's services are usually declared with public visibility so that they can be invoked by clients Public methods are also called service methods A method created simply to assist a service method is called a support method Since a support method is not intended to be called by a client, it should not be declared with public visibility Private methods sometimes as support methods
204
Visibility Modifiers public private Violate encapsulation Enforce
Variables Provide services to clients Support other methods in the class Methods
205
Driver Programs A driver progam drives the use of other, more interesting parts of a program Driver programs are often used to test other parts of the software The Banking class contains a main method that drives the use of the Account class, exercising its services See Banking.java (page 226) See Account.java (page 227)
206
Method Declarations A method declaration specifies the code that will be executed when the method is invoked (or called) When a method is invoked, the flow of control jumps to the method and executes its code When complete, the flow returns to the place where the method was called and continues The invocation may or may not return a value, depending on how the method is defined
207
Method Control Flow The called method can be within the same class, in which case only the method name is needed myMethod(); myMethod compute
208
Method Control Flow The called method can be part of another class or object obj.doIt(); main doIt helpMe helpMe();
209
Method Header A method declaration begins with a method header
char calc (int num1, int num2, String message) method name parameter list The parameter list specifies the type and name of each parameter The name of a parameter in the method declaration is called a formal argument return type
210
Method Body The method header is followed by the method body
char calc (int num1, int num2, String message) { int sum = num1 + num2; char result = message.charAt (sum); return result; } sum and result are local data They are created each time the method is called, and are destroyed when it finishes executing The return expression must be consistent with the return type
211
The return Statement The return type of a method indicates the type of value that the method sends back to the calling location A method that does not return a value has a void return type A return statement specifies the value that will be returned return expression; Its expression must conform to the return type
212
Parameters Each time a method is called, the actual parameters in the invocation are copied into the formal parameters ch = obj.calc (25, count, "Hello"); char calc (int num1, int num2, String message) { int sum = num1 + num2; char result = message.charAt (sum); return result; }
213
Local Data Local variables can be declared inside a method
The formal parameters of a method create automatic local variables when the method is invoked When the method finishes, all local variables are destroyed (including the formal parameters) Keep in mind that instance variables, declared at the class level, exists as long as the object exists Any method in the class can refer to instance data
214
Constructors Revisited
Recall that a constructor is a special method that is used to initialize a newly created object 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 If it has it is no more constructor but a regular method that happen to have the same name as the class it typically sets the initial values of instance variables The programmer does not have to define a constructor for a class
215
Overloading Methods Method overloading is the process of using the same method name for multiple methods The signature of each overloaded method must be unique The signature includes the number, type, and order of the parameters The compiler determines which version of the method is being invoked by analyzing the parameters The return type of the method is not part of the signature
216
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
217
Overloaded Methods The println method is overloaded: and so on...
println (String s) println (int i) println (double d) and so on... The following lines invoke different versions of the println method: System.out.println ("The total is:"); System.out.println (total);
218
Overloading Methods Constructors can be overloaded
Overloaded constructors provide multiple ways to initialize a new object See SnakeEyes.java (page 236) See Die.java (page 237)
219
Part of Die.java public class Die { private final int MIN_FACES = 4;
private int numFaces; // number of sides on the die private int faceValue; // current value showing on the die public Die () numFaces = 6; faceValue = 1; } public Die (int faces) if (faces < MIN_FACES) else numFaces = faces;
220
Method Decomposition A method should be relatively small, so that it can be understood as a single entity A potentially large method should be decomposed into several smaller methods as needed for clarity A service method of an object may call one or more support methods to accomplish its goal Support methods could call other support methods if appropriate
221
Example Pig Latin The process of translating an English sentence into Pig Latin can be decomposed into the process of translating each word The process of translating a word can be decomposed into the process of translating words that begin with vowels begin with consonant blends (sh, cr, tw, etc.) begins with single consonants See PigLatin.java (page 238) See PigLatinTranslator.java (page 240)
222
Class Diagrams Revisited
In a UML class diagram, public members can be preceded by a plus sign Private members are preceded by a minus sign A class diagram for the PigTranslator program: PigLatin + main (args : String[]) : void + translate (sentence : String) : String - translateWord (word : String) : String - beginsWithVowel (word : String) : boolean - beginsWithBlend (word : String) : boolean 1 PigLatinTranslator
223
Object Relationships Objects can have various types of relationships to each other A general association, as we've seen in UML diagrams, is sometimes referred to as a use relationship A general association indicates that one object (or class) uses or refers to another object (or class) in some way We could even annotate an association line in a UML diagram to indicate the nature of the relationship Author Book writes
224
Object Relationships Some use associations occur between objects of the same class For example, we might add two Rational number objects together as follows: r3 = r1.add(r2); One object (r1) is executing the method and another (r2) is passed as a parameter See RationalNumbers.java (page 244) See Rational.java (page 246)
225
Aggregation An aggregate object is an object that contains references to other objects It is (at least in part) composed out of other objects For example, an Account object contains a reference to a String object (the owner's name) An aggregate object represents a has-a relationship A bank account has a name Likewise, a student may have one or more addresses See StudentBody.java (page 250) See Student.java (page 252) See Address.java (page 253)
226
Aggregation in UML An aggregation association is shown in a UML class diagram using an open diamond at the aggregate end StudentBody + main (args : String[]) : void + toString() : String 1 2 Student - firstName : String - lastName : String - homeAddress : Address - schoolAddress : Address - streetAddress : String - city : String - state : String - zipCode : long Address
227
Applet Methods In previous examples we've used the paint method of the Applet class to draw on an applet The Applet class has several methods that are invoked automatically at certain points in an applet's life The init method, for instance, is executed only once when the applet is initially loaded The start and stop methods are called when the applet becomes active or inactive The Applet class also contains other methods that generally assist in applet processing
228
Graphical Objects Any object we define by writing a class can have graphical elements The object must simply obtain a graphics context (a Graphics object) in which to draw An applet can pass its graphics context to another object just as it can any other parameter See LineUp.java (page 257) See StickFigure.java (page 259)
229
Summary Chapter 4 has focused on: class definitions
encapsulation and Java modifiers method declaration, invocation, and parameter passing method overloading method decomposition graphics-based objects
230
CSI 1102 Introduction to Software Design
Prof. Dr.-Ing. Abdulmotaleb El Saddik University of Ottawa (SITE 5-037) (613) x 6277 site.uottawa.ca mcrlab.uottawa.ca
231
Enhancing Classes Now we can explore various aspects of classes and objects in more detail Chapter 5 focuses on: object references and aliases passing objects references as parameters the static modifier wrapper classes nested classes and inner classes interfaces dialog boxes GUI components, events, and listeners
232
References Recall from Chapter 2 that an object reference variable holds the memory address of an object Rather than dealing with arbitrary addresses, we often depict a reference graphically as a “pointer” to an object ChessPiece bishop1 = new ChessPiece(); bishop1
233
The null Reference An object reference variable that does not currently point to an object is called a null reference An attempt to follow a null reference causes a NullPointerException to be thrown For example String name; declares an object reference variable, but does not create a String object for it to refer to Therefore, the variable name contains a null reference
234
The null Reference Class NameIsNull {
String name; // not initialized therefore null Public void printName() { System.out.println(name.length()); // this will cause an exception }
235
The this Reference The this reference allows an object to refer to itself Inside a method, the this reference can be used to refer to the currently executing object For example, if(this.position == piece2.position) result = false; clarifies which position is being referenced The this reference refers to the object through which the method containing the code was invoked
236
The this reference The this reference can also distinguish the parameters of a constructor from the corresponding instance variables with the same names Public Account (Sring owner, long account, double initial) { name = owner; acctNumber = account; balance = initial; }
237
The this reference The this reference can also distinguish the parameters of a constructor from the corresponding instance variables with the same names Public Account (Sring name, long acctNumber, double balance) { this.name = name; this.acctNumber = acctNumber; this.balance = balance; }
238
Assignment Revisited The act of assignment takes a copy of a value and stores it in a variable For primitive types: num2 = num1; Before After num1 5 num2 num1 num2 5 12
239
Reference Assignment For object references, assignment copies the memory location: bishop2 = bishop1; Before bishop1 bishop2 After bishop1 bishop2
240
Aliases Two or more references that refer to the same object are called aliases of each other One object (and its data) can be accessed using different reference variables Aliases can be useful, but should be managed carefully Changing the object’s state (its variables) through one reference changes it for all of its aliases
241
Testing Objects for Equality
The == operator compares object references for equality, returning true if the references are aliases of each other A method called equals is defined for all objects, but unless we redefine it when we write a class, it has the same semantics as the == operator bishop1.equals(bishop2); returns true if both references refer to the same object We can redefine the equals method to return true under whatever conditions we think are appropriate
242
Garbage Collection All interaction with an object occurs through a reference variable An object is used if we have a reference to it When an object no longer has any valid references to it, it can no longer be accessed by the program It is useless, and is called garbage Java performs automatic garbage collection periodically, returning an object's memory to the system for future use Java Runtime Environment executes a methods that collects all objects marked as garbage
243
Passing Objects as Parameters
Parameters in a Java method are passed by value This means that a copy of the actual parameter (the value passed in) is stored into the formal parameter (in the method header) Passing parameters is essentially like an assignment statement When an object is passed to a method, the actual parameter and the formal parameter become aliases of each other
244
Passing Objects to Methods
What you do using a parameter inside a method may or may not have a permanent effect (outside the method) See ParameterPassing.java (page xxx) See ParameterTester.java (page xxx) See Num.java (page xxx) Note the difference between changing the reference and changing the object that the reference points to
245
ParameterPassing.java public class ParameterPassing {
// sets up 3 variables and illustrate parameter passing public static void main (String [] args) { ParameterTester tester = new ParameterTester(); int a1 = 111; Num a2 = new Num (222); Num a3 = new Num (333); System.out.println("Before ChangeValues: "); System.out.println("a1 a2 a3: " + a1 + " " + a2 + " " + a3); tester.changeValues(a1, a2, a3); System.out.println("After ChangeValues: "); System.out.println("a1 a2 a3: " + a1 + " " + a2 + " " + a3); } }
246
ParameterTester.java public class ParameterTester {
public void changeValues(int f1, Num f2, Num f3) { System.out.println("Before changing the values: "); System.out.println("f1 f2 f3: " + f1 + " " + f2 + " " + f3); f1 = 999; f2.setValue(888); f3 = new Num(777); System.out.println("After changing the values: "); System.out.println("f1 f2 f3: " + f1 + " " + f2 + " " + f3); } }
247
Num.java public class Num {
private int value; // Constructor public Num (int update) { value = update; } // set up a value public void setValue(int update) { value = update; } // toString public String toString() { return value + " "; } }
248
The results: Parameter passing
Before ChangeValues: a1 a2 a3: Before changing the values: f1 f2 f3: After changing the values: f1 f2 f3: After ChangeValues: a1 a2 a3:
249
What are Static Variables?
Associated with the class rather than with an object Static variables sometimes are called class variables Normally, each object has its own data space If a variable is declared as static, only one copy of the variable exists private static float price; Memory space for a static variable is created when the class in which it is declared is loaded All objects created from the class share access to the static variable Changing the value of a static variable in one object changes it for all others
250
What are Static Variables?
Can we declare Local Variables as static? Can a constant (usually declared through the final modifier) be static?
251
More about Static Methods
Static methods (also called class methods) can be invoked through the class name rather than through a particular object For example, the methods of the Math class are static To make a method static, we apply the static modifier to the method definition Static methods cannot reference instance variables, because instance variables don't exist until an object exists However, they can reference static variables or local variables public static int abs(int num);
252
More about Static Methods: An example
public static int triple (int num) { int result; result = num * 3; return result; } class Helper Because it is static, the method can be invoked as: value = Helper.triple(5);
253
Static Methods and Variables: CountInstances.java
public class CountInstances { public static void main ( String[] args) { Slogan obj; obj = new Slogan("Hello world"); obj = new Slogan("Talk is cheap."); obj = new Slogan("Don't worry, be happy."); System.out.println("Slogans created: " Slogan.getCount()); } }
254
Static Methods and Variables: Slogan.java
public class Slogan { private String phrase; public static int count = 0; // the constructor public Slogan (String str) { phrase = str; count++; //Every time a Slogan object is created count will be incremented by one } // returns the number of objects of this class created public static int getCount() { return count; } }
255
What are Wrapper Classes?
A wrapper class represents a particular primitive type For example Integer ageObj = new Integer (20); uses the Integer class to create an object which effectively represents the integer 20 as an object Why do we need this? This is useful when a program requires an object instead of a primitive type There is a wrapper class in the Java.lang package for each primitive type, see Figure 5.4 Primitive type (PT) Wrapper Class byte Byte int Integer char Character, etc. for other Primitive Types
256
Some methods of the Integer class: See p.287
Integer (int value) // constructor: create a new Integer object byte byteValue () double doubleValue () // Return the value of this integer as the corresponding Primitive Type static int ParseInt (String str) // returns the int corresponding to the value stores in the string static String toBinaryString (int num) // returns a string representation of the integer in the corresponding base
257
Java I/O Java I/O is accomplished using objects that represent streams of data A stream is an ordered sequence of bytes The System.out object represents a standard output stream, which defaults to the monitor screen Reading keyboard input is more complicated… more about it in Chapter 8
258
Keyboard Input Revisited
Input can be read from the keyboard without using the Keyboard class and Wrapper Classes See Wages2.java (page 289): More in Chapter 8 import java.io.*; … BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); String name = in.Readline(); int hours = Integer.parseInt(in.readLine());
259
String myname = new String (“abed”);
String myname = new String ( new String (“abed”) );
260
Nested Classes In addition to containing data and methods, a class can contain another nested class A nested class has access to the variables and methods of the enclosing class, even if they are declared private This is a special relationship and should be used with care Enclosing Class Nested Class
261
Nested Classes A nested class produces a separate bytecode file
If a nested class called Inside is declared in an outer class called Outside, two bytecode files will be produced: Outside.class Outside$Inside.class It is reasonable to declare the variables in an inner class as public so that the (enclosing) outer class can access them.
262
Inner Classes: A Non-static nested class
An inner class is associated with each instance of the enclosing class & can exist only within an instance of an enclosing class public class TestInner { // create and manipulate an outer object public static void main (String[] args) { Outer out = new Outer(); System.out.println(out); out.changeMessage(); System.out.println(out); } }
263
Nested Classes: Outer.java
public class Outer { private int num; private Inner in1, in2; public Outer() { num = 2365; in1 = new Inner ("Hello"); in2 = new Inner ("Hello again"); } public void changeMessage() { in1.message = "Eat desert first"; in2.message = "Another miracle"; } public String toString() { return in1 + "\n" + in2; } Continued…
264
Nested classes: Outer.java
// The inner class private class Inner { public String message; public Inner (String str) { message = str; } public String toString() { num++; return message + "\nOuter number = " + num; } } }
265
Nested classes: The output
Hello Outer number = 2366 Hello again Outer number = 2367 Eat desert first Outer number = 2368 Another miracle Outer number = 2369
266
Interfaces: Useful for software design
None of the methods in an interface are given a definition (body) interface is a reserved word public interface Doable { public void doThis(); public int doThat(); public void doThis2 (float value, char ch); public boolean doTheOther (int num); } A semicolon immediately follows each method header
267
Interfaces in Java A Java interface is a collection of abstract methods and constants An abstract method is a method header without a method body An abstract method can be declared using the modifier abstract, but because all methods in an interface are abstract, usually it is left off An interface is used to define a set of methods formally that a class will implement
268
Interfaces: An example
public class CanDo implements Doable { public void doThis () // whatever } public void doThat () // etc. implements is a reserved word Each method listed in Doable is given a definition
269
More about Interfaces An interface cannot be instantiated
Methods in an interface have public visibility by default A class formally implements an interface by stating so in the class header providing implementations for each abstract method in the interface If a class asserts that it implements an interface, it must define all methods in the interface or the compiler will produce errors. In addition to, or instead of abstract methods, an interface can contain constants When a class implements an interface, it gains access to all its constants
270
Interfaces A class that implements an interface can implement other methods as well A class can implement multiple interfaces class ManyThings implements interface 1, interface2, interface3 { // all methods of all interfaces } The interfaces are listed in the implements clause, separated by commas The class must implement all methods in all interfaces listed in the header
271
More about Interfaces The Java standard class library contains many helpful interfaces The Comparable interface contains an abstract method called compareTo, which is used to compare two objects The String class implements Comparable which gives us the ability to put strings in alphabetical order The Iterator interface contains methods that allow the user to move easily through a collection of objects
272
The Comparable Interface
The Comparable interface provides a common mechanism for comparing one object to another if (obj1.compareTo(obj2) < 0) System.out.println (“obj1 is less than obj2”); The result is negative is obj1 is less that obj2, 0 if they are equal, and positive if obj1 is greater than obj2
273
The Iterator Interface
The Iterator interface provides a means of moving through a collection of objects, one at a time The hasNext method returns a boolean result (true if there are items left to process) The next method returns an object The remove method removes the object most recently returned by the next method
274
About GUIs and Dialog Boxes (Much more in Chapter 9)
A Graphical User Interface (GUI) is created with at least three kinds of objects components events listeners A GUI component defines a screen element to display information or to allow the user to interact with the program, including: push buttons, text fields, Labels etc. The Swing package contains a class called JOptionPane that simplifies the creation and use of basic dialog boxes
275
PUSH ME! What is an Dialog Box?
A graphical component used to interact with the user, A message dialog displays an output string An input dialog presents a prompt and a single input text field A confirm dialog presents the user with a simple “yes-or-no” question PUSH ME!
276
Events An event is an object that represents some activity to which we may want to respond For example, we may want our program to perform some action 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 Events often correspond to user actions, but not always
277
Events and Listeners The Java standard class library contains several classes that represent typical events Certain objects, such as an applet or a graphical button, generate (fire) an event when it occurs Other objects, called listeners, wait for events to occur We can write listener objects to do whatever we want when an event occurs
278
About Events and Listeners
Generator This object may generate an event Listener This object waits for and responds to an event When an event occurs, the generator calls the appropriate method of the listener, passing an object that describes the event
279
Listener Interfaces We can create a listener object by writing a class that implements a particular listener interface The Java standard class library contains several interfaces that correspond to particular event categories For example, the MouseListener interface contains methods that correspond to mouse events After creating the listener, we add the listener to the component that might generate the event to set up a formal relationship between the generator and listener
280
An event listener: PushCounter.java (an extract)
import java.awt.*; import java.awt.event.*; import javax.swing.*; public class PushCounter extends JApplet { private int pushes … This.AddActionListener(new MyListener()); public void int () pushes = 0; push = new JButton(“PUSH ME!”); push.AddActionListener(new ButtonListener()); } PUSH ME!
281
Summary: Enhancing Classes
Understand what the following entails Different object references and aliases Passing objects (references) as parameters The static modifier: static variables and methods Wrapper classes for primitive data types Nested and inner classes Interfaces for software design GUI components, dialog boxes, events, and listeners
282
Thank You!
283
CSI 1102 Introduction to Software Design
Prof. Dr.-Ing. Abdulmotaleb El Saddik University of Ottawa (SITE 5-037) (613) x 6277 site.uottawa.ca mcrlab.uottawa.ca
284
Arrays Arrays are objects that help us organize large amounts of information Chapter 6 focuses on: array declaration and use passing arrays and array elements as parameters arrays of objects sorting elements in an array multidimensional arrays the ArrayList class polygons and polylines more button components
285
Each value has a numeric index
Arrays An array is an ordered list of values scores The entire array has a single name Each value has a numeric index An array of size N is indexed from zero to N-1 This array holds 10 values that are indexed from 0 to 9
286
Arrays A particular value in an array is referenced using the array name followed by the index in brackets For example, the expression scores[2] refers to the value 94 (which is the 3rd value in the array) That expression represents a place to store a single integer which can be used wherever an integer variable can be used
287
Arrays For example, value in an array can be assigned a value, printed, or used in a calculation scores[2] = 89; scores[first] = scores[first] + 2; mean = (scores[0] + scores[9])/2; System.out.println (“Top = “ + scores[5]);
288
Arrays An array stores multiple values of the same type
That type can be primitive types or object references Therefore, we can create an array of integers, or an array of characters, or an array of String objects, etc. In Java, the array itself is an object Therefore the name of the array is a object reference variable, and the array itself must be instantiated
289
Declaring Arrays The scores array could be declared as follows:
int[] scores = new int[10]; Note that the type of the array does not specify its size, but each object of that type has a specific size The type of the variable scores is int[] (an array of integers) It is set to a new array object that can hold 10 integers See BasicArray.java (page xxx)
290
BasicArray.java public class BasicArray { final static int LIMIT = 15;
final static int MULTIPLE = 10; // // Creates an array, fills it with various integer values, // modifies one value, then prints them out. public static void main (String[] args) int[] list = new int[LIMIT]; // Initialize the array values for (int index = 0; index < LIMIT; index++) list[index] = index * MULTIPLE; list[5] = 999; // change one array value System.out.print (list[index] + " "); System.out.println (); }
291
Declaring Arrays Some examples of array declarations:
float[] prices = new float[500]; boolean[] flags; flags = new boolean[20]; char[] codes = new char[1750];
292
Bounds Checking Once an array is created, it has a fixed size
An index used in an array reference must specify a valid element That is, the index value must be in bounds (0 to N-1) The Java interpreter throws an ArrayIndexOutOfBoundsException if an array index is out of bounds This is called automatic bounds checking
293
Bounds Checking For example, if the array codes can hold 100 values, it can be indexed using only the numbers 0 to 99 If count has the value 100, then the following reference will cause an exception to be thrown: System.out.println (codes[count]); It’s common to introduce off-by-one errors when using arrays problem for (int index=0; index <= 100; index++) codes[index] = index*50 + epsilon;
294
Bounds Checking Each array object has a public constant called length that stores the size of the array It is referenced using the array name (just like any other object): scores.length Note that length holds the number of elements, not the largest index See ReverseOrder.java (page xxx) See LetterCount.java (page xxx)
295
ReverseOrder.java import cs1.Keyboard; public class ReverseOrder {
public static void main (String[] args) double[] numbers = new double[10]; System.out.println ("The size of the array: " numbers.length); for (int index = 0; index < numbers.length; index++) System.out.print (“ Enter number " + (index+1) + ": "); numbers[index] = Keyboard.readDouble(); } System.out.println ("The numbers in reverse order:"); for (int index = numbers.length-1; index >= 0; index--) System.out.print (numbers[index] + " "); System.out.println ();
296
LetterCount.java import cs1.Keyboard; public class LetterCount {
public static void main (String[] args) final int NUMCHARS = 26; int[] upper = new int[NUMCHARS]; int[] lower = new int[NUMCHARS]; char current; // the current character being processed int other = 0; // counter for non-alphabetics System.out.println ("Enter a sentence:"); String line = Keyboard.readString(); // Count the number of each letter occurence
297
LetterCount.java for (int ch = 0; ch < line.length(); ch++) {
current = line.charAt(ch); if (current >= 'A' && current <= 'Z') upper[current-'A']++; else if (current >= 'a' && current <= 'z') lower[current-'a']++; other++; } // Print the results System.out.println (); for (int letter=0; letter < upper.length; letter++) System.out.print ( (char) (letter + 'A') ); System.out.print (": " + upper[letter]); System.out.print ("\t\t" + (char) (letter + 'a') ); System.out.println (": " + lower[letter]); System.out.println ("Non-alphabetic characters: " + other);
298
Alternate Array Syntax
The brackets of the array type can be associated with the element type or with the name of the array Therefore the following declarations are equivalent: float[] prices; float prices[]; The first format generally is more readable
299
Initializer Lists An initializer list can be used to instantiate and initialize an array in one step The values are delimited by braces and separated by commas Examples: int[] units = {147, 323, 89, 933, 540, 269, 97, 114, 298, 476}; char[] letterGrades = {'A', 'B', 'C', 'D', ’E'};
300
Initializer Lists Note that when an initializer list is used:
the new operator is not used no size value is specified The size of the array is determined by the number of items in the initializer list An initializer list can only be used only in the declaration of an array See Primes.java (page xxx)
301
Primes.java public class Primes {
// // Stores some prime numbers in an array and prints them. public static void main (String[] args) int[] primeNums = {2, 3, 5, 7, 11, 13, 17, 19}; System.out.println ("Array length: " primeNums.length); System.out.println ("The first few prime numbers are:"); for (int scan = 0; scan < primeNums.length; scan++) System.out.print (primeNums[scan] + " "); System.out.println (); }
302
Arrays as Parameters An entire array can be passed as a parameter to a method Like any other object, the reference to the array is passed, making the formal and actual parameters aliases of each other Changing an array element within the method changes the original An array element can be passed to a method as well, and follows the parameter passing rules of that element's type
303
Arrays of Objects The elements of an array can be object references
The following declaration reserves space to store 25 references to String objects String[] words = new String[25]; It does NOT create the String objects themselves Each object stored in an array must be instantiated separately See GradeRange.java (page xxx)
304
GradeRange.java public class GradeRange {
// // Stores the possible grades and their // numeric lowest value, then prints them out. public static void main (String[] args) String[] grades = {"A", "A-", "B+", "B", "B-", "C+", "C", "C-","D+", "D", "D-", "F"}; int[] cutoff = {95, 90, 87, 83, 80, 77, 73, 70, , 63, 60, 0}; for (int level = 0; level < cutoff.length; level++) System.out.println (grades[level] + "\t" cutoff[level]); }
305
Command-Line Arguments
The signature of the main method indicates that it takes an array of String objects as a parameter These values come from command-line arguments that are provided when the interpreter is invoked For example, the following invocation of the interpreter passes an array of three String objects into main: > java DoIt pennsylvania texas california These strings are stored at indexes 0-2 of the parameter See NameTag.java (page xxx)
306
NameTag.java public class NameTag {
// // Prints a simple name tag using a greeting and a // name that is specified by the user. public static void main (String[] args) System.out.println (); System.out.println (" " + args[0]); System.out.println ("My name is " + args[1]); }
307
Arrays of Objects Objects can have arrays as instance variables
Therefore, many useful structures can be created simply with arrays and objects The software designer must determine carefully an organization of data and objects that makes sense for the situation See Tunes.java (page xxx) See CDCollection.java (page xxx) See CD.java (page xxx)
308
Extract from CDCollection.java (1)
public class CDCollection { private CD[] collection; private int count; private int currentSize; public CDCollection () currentSize = 100; collection = new CD[currentSize]; count = 0; } public void addCD (...) if (count == currentSize) increaseSize(); collection[count] = new CD (...); count++;
309
Extract from CDCollection.java (2)
private void increaseSize () { currentSize *= 2; CD[] temp = new CD[currentSize]; for (int cd = 0; cd < collection.length; cd++) temp[cd] = collection[cd]; collection = temp; }
310
Sorting Sorting is the process of arranging a list of items in a particular order There must be some value on which the order is based There are many algorithms for sorting a list of items These algorithms vary in efficiency We will examine two specific algorithms: Selection Sort Insertion Sort
311
Selection Sort The approach of Selection Sort:
select a value and put it in its final place into the sort list repeat for all other values 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 in their proper places
312
Selection Sort An example: See SortGrades.java (page 289)
original: smallest is 1: smallest is 2: smallest is 3: smallest is 6: (smallest is 9) sorted: See SortGrades.java (page 289) See Sorts.java (page 290) -- the selectionSort method
313
Swapping Swapping is the process of exchanging two values
Swapping requires three assignment statements temp = first; first = second; second = temp;
314
Insertion Sort 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 In more detail: consider the first item to be a sorted sublist (of one item) insert the second item into the sorted sublist, shifting the first item as needed to make room to insert the new addition insert the third item into the sorted sublist (of two items), shifting items as necessary repeat until all values are inserted into their proper positions
315
Insertion Sort An example:
original: (insert 3) insert 9: insert 6: insert 1: insert 2: sorted: See Sorts.java (page 290) -- the insertionSort method 3 3 9
316
Sorting Objects Integers have an inherent order, but the order of a collection of objects must be defined by the person defining the class Recall that a Java interface can be used as a type name and guarantees that a particular class implementes particular methods We can use the Comparable interface and the CompareTo method to develop a generic sort for a set of objects See SortPhoneList.java (page xxx) See Contact.java (page xxx) See Sorts.java (page xxx)
317
From Sorts.java public static void insertionSort (Comparable[] objects) { for (int index = 1; index < objects.length; index++) Comparable key = objects[index]; int position = index; // shift larger values to the right while (position > 0 && objects[position-1].compareTo(key) > 0) objects[position] = objects[position-1]; position--; } objects[position] = key;
318
Comparing Sorts Both Selection and Insertion sorts are similar in efficiency The both have outer loops that scan all elements, and inner loops that compare the value of the outer loop with almost all values in the list Therefore approximately n2 number of comparisons are made to sort a list of size n We therefore say that these sorts are of order n2 Other sorts are more efficient: order n log2 n
319
Two-Dimensional Arrays
A one-dimensional array stores a simple list of values A two-dimensional array can be thought of as a table of values, with rows and columns Because each dimension is an array of array references, the arrays within one dimension can be of different lengths Sometimes these are called ragged arrays
320
Two-Dimensional Arrays
A two-dimensional array element is referenced using two index values value = scores [3][6] To be precise, a two-dimensional array in Java is an array of arrays
321
Two-Dimensional Arrays
From TwoDArray.java public static void main (String[] args) { int[][] table = new int[5][10]; // Load the table with values for (int row=0; row < table.length; row++) for (int col=0; col < table[row].length; col++) table[row][col] = row * 10 + col; // Print the table System.out.print (table[row][col] + "\t"); System.out.println(); } See TwoDArray.java (page xxx) See SodaSurvey.java (page xxx)
322
Multidimensional Arrays
An array can have many dimensions If it has more than one dimension, it is called a multidimensional array Each dimension subdivides the previous one into the specified number of elements Each array dimension has its own length constant
323
The ArrayList Class The ArrayList class is part of the java.util package Like an array, it can store a list of values and reference them with an index Unlike an array, an ArrayList object grows and shrinks as needed Items can be inserted or removed with a single method invocation It stores references to the Object class
324
Some Methods of the ArrayList Class
import java.util.ArrayList; public class Beatles { public static void main (String[] args) ArrayList band = new ArrayList(); band.add ("Paul"); band.add ("Pete"); band.add ("John"); band.add ("George"); System.out.println (band); int location = band.indexOf ("Pete"); band.remove (location); System.out.println ("At index 1: " + band.get(1)); band.add (2, "Ringo"); System.out.println ("Size of the band: " + band.size()); } See Beatles.java (page xxx)
325
ArrayList Efficiency The ArrayList class is implemented using an array. The array expands beyond its initial capacity to accommodate additional elements Methods manipulate the array so that indexes remain continuous as elements are added or removed
326
Polygons and Polylines
Arrays often are helpful in graphics processing Polygons and polylines are shapes that can be defined by values stored in arrays A polyline is similar to a polygon except that its endpoints do not meet, and it cannot be filled See Rocket.java (page xxx)
327
The Polygon Class The Polygon class, defined in the java.awt package can be used to define and draw a polygon Two versions of the overloaded drawPolygon and fillPolygon methods take a single Polygon object as a parameter A Polygon object encapsulated the coordinates of the polygon
328
Other Button Components
A check box is a button that can be toggled on or off A check box is represented by the JCheckBox class A change of state generates an item event See StyleOptions.java (page xxx) See StyleGUI.java(page xxx)
329
The Font Class A Font object is defined by the font name, the font style, and the font size The style of a font can be plain, bold, italic, or bold and italic together The itemStateChanged method of the listener responds when a check box changes state
330
Radio Buttons A set of radio buttons represents a set of mutually exclusive options When a radio button from a group is selected, the other button currently on in the group is toggled off A radio button generates an action event See QuoteOptions.java (page xxx) See QuoteGUI.java (page xxx)
331
Summary Chapter 6 has focused on: array declaration and use
passing arrays and array elements as parameters arrays of objects sorting elements in an array multidimensional arrays the ArrayList class polygons and polylines more button components
332
Thank You! Dankie
333
Abdulmotaleb El Saddik University of Ottawa
CSI 1102 Abdulmotaleb El Saddik University of Ottawa School of Information Technology and Engineering (SITE) Multimedia Communications Research Laboratory (MCRLab) Distributed Collaborative Virtual Environments (DISCOVER) mcrlab.uottawa.ca
334
Introduction to Software Design
Chapter 7: Inheritance Presentation slides for Introduction to Software Design Java Software Solutions is published by Addison-Wesley
335
Inheritance Another fundamental object-oriented technique is called inheritance, for organizing and creating classes and for promoting reuse Chapter 7 focuses on: deriving new classes from existing classes creating class hierarchies the protected modifier polymorphism via inheritance inheritance hierarchies for interfaces inheritance used in graphical user interfaces
336
Inheritance Inheritance allows a software developer to derive a new class from an existing one The existing class is called the parent class, or super class, or base class The derived class is called the child class or subclass. As the name implies, the child inherits characteristics of the parent That is, the child class inherits the methods and data defined for the parent class
337
Inheritance To tailor a derived class, the programmer can add new variables or methods, or can modify the inherited ones Software reuse is at the heart of inheritance By using existing software components to create new ones, we capitalize on all the effort that went into the design, implementation, and testing of the existing software
338
Inheritance Inheritance relationships often are shown graphically in a class diagram, with the arrow pointing to the parent class Vehicle Car Inheritance should create an is-a relationship, meaning the child is a more specific version of the parent
339
Deriving Subclasses In Java, we use the reserved word extends to establish an inheritance relationship class Car extends Vehicle { // class contents } See Words.java (page xxx) See Book.java (page xxx) See Dictionary.java (page xxx)
340
Words.java public class Words {
/** Instantiates a derived class and invokes its inherited and local methods. */ public static void main (String[] args) Dictionary webster = new Dictionary (); webster.pageMessage(); webster.definitionMessage(); }
341
Book.java public class Book { protected int pages = 1500;
// // Prints a message about the pages of this book. // public void pageMessage () System.out.println ("Number of pages: " pages); }
342
Dictionary.java public class Dictionary extends Book {
private int definitions = 52500; // // Prints a message using both local and inherited values. // public void definitionMessage () System.out.println ("Number of definitions: " + definitions); System.out.println ("Definitions per page: “ definitions/pages); }
343
The Book and Dictionary Classes
# pages : int + pageMessage () : void Words Dictionary - definition : int +main (args : String[]) : void + definitionMessage () : void
344
The protected Modifier
Visibility modifiers determine which class members are inherited and which are not Variables and methods declared with public visibility are inherited; those with private visibility are not But public variables violate the principle of encapsulation There is a third visibility modifier that helps in inheritance situations: protected
345
The protected Modifier
The protected visibility modifier allows a member of a base class to be inherited into a child protected visibility provides more encapsulation than public does However, protected visibility is not as tightly encapsulated as private visibility The details of each modifier are given in the Appendix of the text book
346
The super Reference Constructors are not inherited, even though they have public visibility Yet we often want to use the parent's constructor to set up the "parent's part" of the object The super reference can be used to refer to the parent class, and often is used to invoke the parent's constructor See Words2.java (page xxx) See Book2.java (page xxx) See Dictionary2.java (page xxx)
347
Words2.java public class Words2 {
// // Instantiates a derived class and invokes its // inherited and local methods. // public static void main (String[] args) Dictionary2 webster = new Dictionary2 (1500, 52500); webster.pageMessage(); webster.definitionMessage(); }
348
Book2.java public class Book2 { protected int pages;
// //Sets up the book with the specified number of pages. // public Book2 (int numPages) { pages = numPages; } // Prints a message about the pages of this book. // public void pageMessage () { System.out.println ("Number of pages: " + pages);
349
Dictionary2.java public class Dictionary2 extends Book2 {
private int definitions; // // Sets up the dictionary with the specified number of pages // (maintained by the Book parent class) and defintions. // public Dictionary2 (int numPages, int numDefinitions) super (numPages); definitions = numDefinitions; } // Prints a message using both local and inherited values. // public void definitionMessage () System.out.println ("Number of definitions: " + definitions); System.out.println ("Definitions per page: " + definitions/pages);
350
The super Reference A child’s constructor is responsible for calling the parent’s constructor The first line of a child’s constructor should use the super reference to call the parent’s constructor The super reference can be used to reference other variables and methods defined in the parent’s class
351
Single vs. Multiple Inheritance
Basically: Java supports single inheritance, meaning that a derived class can have only one parent class Multiple inheritance, in some other languages, allows a class to be derived from two or more classes, inheriting the members of all parents Java multiple inheritance is achieved through Interfaces Collisions, such as the same variable name in two parents, have to be resolved In most cases, the use of interfaces gives us aspects of multiple inheritance without the overhead
352
Overriding Methods A child class can override the definition of an inherited method in favor of its own That is, a child can redefine a method that it inherits from its parent The new method must have the same signature as the parent's method, but can have a different body The type of the object executing the method determines which version of the method is invoked
353
Overriding Methods See Messages.java (page xxx)
See Thought.java (page xxx) See Advice.java (page xxx)
354
Messages.java public class Messages {
// // Instatiates two objects a invokes the message method in each. public static void main (String[] args) Thought parked = new Thought(); Advice dates = new Advice(); parked.message(); dates.message(); // overridden }
355
Thought.java public class Thought {
// // Prints a message. public void message() System.out.println ("I feel like I'm diagonally parked in a " "parallel universe."); System.out.println(); }
356
Advice.java public class Advice extends Thought {
// // Prints a message. This method overrides the parent's version. // It also invokes the parent's version explicitly using super. public void message() System.out.println ("Warning: Dates in calendar are closer " + "than they appear."); System.out.println(); super.message(); }
357
Overriding Methods and Variables
Note that a parent method can be invoked explicitly using the super reference If a method is declared with the final modifier, it cannot be overridden The concept of overriding can be applied to data (called shadowing variables), but generally it should be avoided
358
Overloading vs. Overriding
Don't confuse the concepts of overloading and overriding Overloading deals with multiple methods in the same class with the same name but different signatures Overriding deals with two methods, one in a parent class and one in a child class, that have the same signature Overloading lets you define a similar operation in different ways for different data Overriding lets you define a similar operation in different ways for different object types
359
Class Hierarchies A child class of one parent can be the parent of another child, forming a class hierarchy Business RetailBusiness ServiceBusiness KMart Macys Kinkos
360
Class Hierarchies Two children of the same parent are called siblings
Good class design puts all common features as high in the hierarchy as is reasonable An inherited member is passed continually down the line The inheritance mechanism is transitive. That is, a child class inherits from all its ancestor classes
361
Class Hierarchies There is no single class hierarchy that is appropriate for all situations Class hierarchies often need to be extended and modified to keep up with changes
362
The Object Class A class called Object is defined in the java.lang package 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 an existing class, it is assumed to be the child of the Object class Therefore, the Object class is the ultimate root of all class hierarchies
363
The Object Class The Object class contains a few useful methods, which are inherited by all classes For example, the toString method is defined in the Object class Every time we have defined toString, we have actually been overriding an existing definition The toString method in the Object class is defined to return a string that contains the name of the object’s class together with other information
364
The Object Class That’s why the println method can call toString for any object that is passed to it – all objects are guaranteed to have a toString method via inheritance See Academia.java (page xxx) See Student.java (page xxx) See GradStudent.java (page xxx)
365
The object Class The equals method of the Object class determines if two references are aliases We can override equals to define equality in some more appropriate way
366
Thank You! Ευχαριστώ Dankie WAD MAHAD SAN TAHAY GADDA GUEY
367
End Mark = Max (A || B) A = SUM (ASS1-4 + Midterm + FInal) B = SUM (ASS1-4 + FInal)
368
Abstract Classes An abstract class is a placeholder in a class hierarchy that represents a generic concept An abstract class cannot be instantiated We use the modifier abstract on the class header to declare a class as abstract abstract public class vehicle
369
Abstract Classes An abstract class often contains abstract methods with no definitions (like an interface does), though it doesn’t need to Unlike an interface, the abstract modifier must be applied to each abstract method An abstract class typically contains non-abstract methods with method bodies, further distinguishing abstract classes from interfaces A class declared as abstract does not need to contain abstract methods
370
What are Abstract Classes?
The child of an abstract class must override the abstract methods of the parent, or it too will be considered abstract An abstract method cannot be defined as final (because it must be overridden) or static (because it has no definition yet) The use of abstract classes is a design decision; it helps us establish common elements in a class that is too general to instantiate E.g. Vehicle, FuelConsumption E.g. Employee, BenefitsCalculation
371
References and Inheritance
An object reference can refer to an object of its class, or to an object of any class related to it by inheritance For example, if the Holiday class is used to derive a child class called Christmas, then a Holiday reference could be used to point to a Christmas object Holiday Christmas Holiday day; day = new Christmas();
372
References and Inheritance
Widening conversion: Assigning a predecessor object to an ancestor reference Performed by simple assignment Narrowing conversion: Assigning an ancestor object to a predecessor reference Performed with a cast Carrying this to the limit, an Object reference can be used to refer to any object An ArrayList is designed to hold Object references
373
Indirect Use of Noninherited Members
An inherited member can be referenced directly by name in the 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 403) See FoodItem.java (page 404) See Pizza.java (page 405)
374
Polymorphism: Having many forms
A reference can be polymorphic, which can be defined as "having many forms“ A polymorphic reference variable can refer to different types of objects during execution Polymorphic references are resolved at run time; this is called dynamic binding Careful use of polymorphic references can lead to elegant, robust software designs Mammal pet; Horse myhorse = new Horse(); // Horse derived from Mammal // Horse is-a Mammal pet = myhorse;
375
Polymorphism via Interfaces
An interface name can be used as the type of an object reference variable Doable obj; The obj reference can be used to point to any object of any class that implements the Doable interface The version of doThis that the following line invokes depends on the type of object that obj is referring to obj.doThis();
376
Polymorphism via Inheritance
Suppose the Holiday class has a method called celebrate, and the Christmas class overrides it Now consider the following invocation: day.celebrate(); If day refers to a Holiday object, it invokes the Holiday version of celebrate; if it refers to a Christmas object, it invokes the Christmas version
377
Polymorphism via Inheritance
Consider the following class hierarchy: StaffMember Volunteer Employee Executive Hourly
378
Polymorphism via Inheritance
Now consider the task of paying all employees See Firm.java (page xxx) See Staff.java (page xxx) See StaffMember.java (page xxx) See Volunteer.java (page xxx) See Employee.java (page xxx) See Executive.java (page xxx) See Hourly.java (page xxx)
379
Firm.java public class Firm { public static void main (String[] args) { Staff personnel = new Staff(); personnel.payday(); } }
380
Staff.java public class Staff { private StaffMember[] staffList; public Staff() { staffList = new StaffMember[4]; staffList[0] = new Executive("Sam", " ", ); staffList[1] = new Employee("Joe", " ", ); staffList[2] = new Volunteer("Sue", " "); staffList[3] = new Volunteer("Ann", " "); } public void payday() { double amount; for (int count = 0; count < staffList.length; count++) { System.out.println(staffList[count]); amount = staffList[count].pay(); if (amount == 0) System.out.println("Thanks!"); else System.out.println("Paid: " + amount); } } }
381
StaffMember.java abstract public class StaffMember { protected String name; protected String phone; public StaffMember(String eName, String ePhone) { name = eName; phone = ePhone; } public String toString() { String result = "Name: " + name + "\n"; result += "Phone: " + phone; return result; } public abstract double pay(); }
382
Volunteer.java public class Volunteer extends StaffMember { public Volunteer (String eName, String ePhone) { super(eName, ePhone); } public double pay() { return 0.0; } }
383
Employee.java public class Employee extends StaffMember { protected double payRate; public Employee(String eName, String ePhone, double rate) { super(eName, ePhone); payRate = rate; } public double pay() { return payRate; } public String toString() { String result = super.toString(); return result; } }
384
Executive.java public class Executive extends Employee { private double bonus; public Executive(String eName, String ePhone, double rate) { super(eName, ePhone, rate); bonus = 1000; } public double pay() { double payment = super.pay() + bonus; return payment; } }
385
Interface Hierarchies
Inheritance can be applied to interfaces as well as to classes One interface can be derived from another interface The child interface inherits all abstract methods of the parent A class implementing the child interface must define all methods from both the ancestor and child interfaces All members of an interface are public Note that class hierarchies and interface hierarchies are distinct (they do not overlap)
386
Polymorphism via Interfaces
An interface name can be used to declare an object reference variable Interfaces allow polymorphic references in which the method that is invoked is determined by the object being referenced A class can implement multiple interfaces The interfaces are listed in the implements clause, separated by commas The class must implement all methods in all interfaces listed in the header
387
Speakers, Philosophers and Dogs
public interface Speaker { public void speak(); public void announce (String str); } Assume Classes Philosopher and Dog both implement the Speaker interface: Speaker guest; guest = new Philosopher(); guest.speak(); speak method in Philosopher class guest = new Dog(); guest.speak; speak method in Dog class
388
Inheritance and GUIs An applet is an excellent example of inheritance
Recall that when we define an applet, we extend the Applet class or the JApplet class The Applet and JApplet classes already handle all the details about applet creation and execution, including the interaction with a Web browser
389
Inheritance and GUIs Our applet classes have to deal only with issues that specifically relate to what our particular applet will do When we define certain methods, such as the paint method of an applet, we are actually overriding a method defined in the Component class, which is ultimately inherited into the Applet class or the JApplet class
390
GUI Components A GUI component is an object that represents a visual entity in an graphical user interface (such as a button or a text field) Components can generate events to which listener objects can respond For example, an applet is a component that can generate mouse events An applet is also a special kind of component, called a container, in which other components can be placed
391
The Component Class Hierarchy
The Java classes that define GUI components are part of a class hierarchy Swing GUI components typically are derived from the JComponent class which is derived from the Container class which is derived from the Component class Many Swing components can serve as (limited) containers, because they are derived from the Container class
393
Extending Event Adapter Classes
Listener classes can be created by implementing a particular interface (such as MouseListener interface) A listener also can be created by extending an event adapter class Each listener interface has a corresponding adapter class (such as the MouseAdapter class) Each adapter class implements the corresponding listener and provides empty method definitions Empty definitions for unused methods need not be provided
394
Summary Chapter 7 has focused on:
deriving new classes from existing classes creating class hierarchies the protected modifier polymorphism via inheritance inheritance hierarchies for interfaces inheritance used in graphical user interfaces
395
Thank You! Ευχαριστώ Dankie WAD MAHAD SAN TAHAY GADDA GUEY
396
Abdulmotaleb El Saddik University of Ottawa
CSI 1102 Abdulmotaleb El Saddik University of Ottawa School of Information Technology and Engineering (SITE) Multimedia Communications Research Laboratory (MCRLab) Distributed Collaborative Virtual Environments (DISCOVER) mcrlab.uottawa.ca
397
Chapter 8: Exceptions (only 8.0)
Presentation slides for Introduction to Software Design
398
Exceptions and I/O Streams
Now we can explore two related topics further: exceptions Chapter 8 focuses on: the try-catch statement exception propagation creating and throwing exceptions
399
Exceptions An exception is an object that describes an unusual or erroneous situation Exceptions are thrown by a program, and may be caught and handled by another part of the program A program can be separated into a normal execution flow and an exception execution flow An error is also represented as an object in Java, but usually represents a unrecoverable situation and should not be caught
400
Exception Handling Java has a predefined set of exceptions and errors that can occur during execution A program can deal with an exception in one of three ways: ignore it If an exception is ignored by the program, the program will terminate abnormally and produce an appropriate message handle it where it occurs To process an exception when it occurs, the line that throws the exception is executed within a try block handle it an another place in the program An exception can be handled at a higher level if it is not appropriate to handle it where it occurs
401
Exception Handling The manner in which an exception is processed is an important design consideration
402
Exception Handling If an exception is ignored by the program, the program will terminate abnormally and produce an appropriate message The message includes a call stack trace that indicates the line on which the exception occurred The call stack trace also shows the method call trail that lead to the attempted execution of the offending line The getMessage method returns a string explaining why the exception was thrown The printStackTrace method prints the call stack trace
403
Zero.java public class Zero { public static void main (String[] args)
// // Deliberately divides by zero to produce an exception. // public static void main (String[] args) int numerator = 10; int denominator = 0; System.out.println (numerator/denominator); System.out.println ("This text will not be printed."); }
404
The first line indicates which Exception was thrown
java.lang.ArithmeticException: / by zero The first line indicates which Exception was thrown at Zero.main(Zero.java:17) Exception in thread "main" Exit code: 1 There were errors The remaining lines are the call stack trace: Where the exception occurred Which methods File name & Line number
405
The try Statement To process an exception when it occurs, the line that throws the exception is executed within a try block A try block is followed by one or more catch clauses, which contain code to process an exception Each catch clause has an associated exception type and is called an exception handler When an exception occurs, processing continues at the first catch clause that matches the exception type
406
Zero2.java }} public class Zero {
// // Deliberately divides by zero to produce an exception. // public static void main (String[] args) { int numerator = 10; int denominator = 0; try System.out.println (numerator / denominator); } catch (ArithmeticException e) System.out.println ("hahahahahaha Exception: " e); System.out.println (" Does not matter "); System.out.println ("This text will be printed."); }}
407
The finally Clause A try statement can have an optional clause following the catch clauses, designated by the reserved word finally The statements in the finally clause always are executed If no exception is generated, the statements in the finally clause are executed after the statements in the try block complete If an exception is generated, the statements in the finally clause are executed after the statements in the appropriate catch clause complete
408
Exception Propagation
An exception can be handled at a higher level if it is not appropriate to handle it where it occurs Exceptions propagate up through the method calling hierarchy until they are caught and handled or until they reach the level of the main method A try block that contains a call to a method in which an exception is thrown can be used to catch that exception See Propagation.java See ExceptionScope.java
409
The Exception Class Hierarchy
Object Throwable Error Exception LinkageError AWTError RunTimeException ClassNotFoundException
410
The throw Statement A programmer can define an exception by extending the Exception class or one of its descendants Exceptions are thrown using the throw statement Usually a throw statement is nested inside an if statement that evaluates the condition to see if the exception should be thrown See CreatingExceptions.java (page xxx) See OutOfRangeException.java (page xxx)
411
CreatingExceptions.java import cs1.Keyboard;
public class CreatingExceptions { // // Creates an exception object and possibly throws it. public static void main (String[] args) throws OutOfRangeException final int MIN = 25, MAX = 40; OutOfRangeException problem = new OutOfRangeException ("Input value is out of range."); System.out.print ("Enter an integer value between " + MIN + " and " + MAX + ", inclusive: "); int value = Keyboard.readInt(); // Determines if the exception should be thrown if (value < MIN || value > MAX) throw problem; System.out.println ("End of main method."); // may never reach }
412
OutOfRangeException.java public class OutOfRangeException extends Exception { // // Sets up the exception object with a particular message. OutOfRangeException (String message) super (message); } Whether to use an exception, a conditional, or a loop is an important design decision Enter an integer value between 25 and 40, inclusive: 78 Exception in Thread “main” OutOfRangeException: Input value is out of range. at CreatingExceptions.main(CreatingExceptions.java:20)
413
Checked Exceptions An exception is either checked or unchecked
A checked exception either must be caught by a method, or must be listed in the throws clause of any method that may throw or propagate it a throws clause is appended to the method header The compiler will complain if a checked exception is not handled appropriately
414
Unchecked Exceptions An unchecked exception does not require explicit handling, though it could be processed that way The only unchecked exceptions in Java are objects of type RuntimeException or any of its descendants Errors are similar to RuntimeException and its descendants Errors should not be caught Errors to not require a throws clause
415
Thank You! Ευχαριστώ Dankie WAD MAHAD SAN TAHAY GADDA GUEY
416
Abdulmotaleb El Saddik University of Ottawa
CSI 1102 Abdulmotaleb El Saddik University of Ottawa School of Information Technology and Engineering (SITE) Multimedia Communications Research Laboratory (MCRLab) Distributed Collaborative Virtual Environments (DISCOVER) mcrlab.uottawa.ca
417
Chapter 10: Software Engineering
Presentation slides for Introduction to Software Design
418
Software Engineering The quality of the software is a direct result of the process we follow to create it Chapter 10 focuses on: software development models the software life cycle and its implications linear vs. iterative development approaches goals and techniques of testing an evolutionary approach to object-oriented development a nontrivial evolutionary development example
419
The Software Life Cycle
The overall life cycle of a program go through 3 fundamentals stages A version of the software that is made available to user is called a release Concept Use Development (4 steps) Maintenance Release End of useful life Bugs report Release
420
Maintenance Maintenance tasks include any modifications to an existing program; it includes enhancements and defect removal (Bugs fixes) The characteristics of a program that make it easy to develop also make it easy to maintain Maintenance efforts tend to far outweigh the development effort in today’s software
421
Development vs. Maintenance
Use and Maintenance
422
Development and Maintenance Effort
Small increases in effort at the development stage greatly reduce maintenance tasks The goal is to minimize the overall effort required to create and to maintain the program Development Maintenance Development Maintenance
423
Development and Maintenance Effort
Often the maintainers of a program are not the program’s original developers Maintainers must be able to understand a program they didn’t design The ability to read and understand a program depends on how clearly the requirements are established how well the program is designed how well the program is implemented how well the program is documented
424
Software Development Models
A software development model is an organized approach to creating quality software Requirements, Design, Coding (implementation) and testing (Remember Chapter 3) Too many programmers follow a build-and-fix approach: They write a program and modify it until it is functional, without regard to system design Errors are addressed unsystematically if and as they are discovered It is not really a development model at all
425
The Build-and-Fix Approach
Write program Modify
426
The Waterfall Model The waterfall model was developed in the early 1970s Activities that must be specifically addressed during development include: Establishing clear and unambiguous requirements Creating a clean design from the requirements Implementing the design Testing the implementation Originally it was proposed as a linear model, without backtracking: One stage followed directly the next
427
It is a nice goal, but it is generally unrealistic
The Waterfall Model Establish requirements Create design Implement code Test system It is a nice goal, but it is generally unrealistic
428
Iterative Development
Iterative development allows the developer to cycle through the different development stages It is essentially the waterfall model with backtracking It should be used as a technique available to the developer to deal with unexpected problems that may arise in later stages of development However backtracking should not be used irresponsibly
429
An Iterative Development Process
Establish requirements Create design Implement code Test system
430
Testing The results of each stage should be evaluated carefully prior to going on to the next stage Running a completed program with various inputs to discover problems Testing is also any action to asses the quality of the software Before moving on to the design, for example, the requirements should be evaluated to ensure completeness, consistency, and clarity A design evaluation should ensure that each requirement was addressed adequately
431
Testing Techniques A design or an implementation may be evaluated during a walkthrough The goal of a walkthrough is to identify problems, not to solve them Presenting our design or code to someone else causes us to think more carefully about it Participants discuss of merits and problems, and create a list of issues that must be addressed
432
Testing Techniques Generally, the goal of testing is to find errors
Often it is called defect testing A good test uncovers problems in a program A test case includes a set of inputs user actions or other initial conditions expected output Document it to reproduce errors if they occure It is not feasible to test every possible case
433
Black-Box Testing Black-box testing maps a set of specific inputs to a set of expected outputs A test case is successful if the input produces the expected output A class can undergo black-box testing if we focus on the system interfaces (public methods) An equivalence category is a collection of input sets Two input sets belong to the same equivalence category if there is reason to believe that if one works, it will work for the other Therefore testing one input set essentially tests the entire category Do not forget to test the test boundary
434
White-Box Testing White-box testing also is referred to as glass-box testing It focuses on the internal logic such as the implementation of a method Statement coverage guarantees that all statements in a method are executed Condition coverage guarantees that all paths through a method are executed Example: In a if-statement we have to test both paths: The true path statement, and The false path statement
435
Prototypes: A way to sell Ideas
A prototype is a program created to explore a particular concept A prototype could also be presented through a set of diagrams Prototyping is more useful, time-effective, and cost-effective than merely acting on an assumption that later may backfire Usually a prototype is created to communicate to the client: a particular task the feasibility of a requirement a user interface It is a way of validating requirements
436
Presenting User Interface SW-Prototype
Return Help Screen You can enter either the person's name or their number. Then hit the place button to call them Computer Telephone Last Name: First Name: Phone: Place Call Help Computer Telephone Last Name: Greenberg First Name: Phone: Place Call Help Connected Hang up Computer Telephone Last Name: Greenberg First Name: Phone: Place Call Help Dialling.... Cancel Computer Telephone Last Name: Greenberg First Name: Phone: Place Call Help Computer Telephone Last Name: First Name: Phone: Place Call Help Computer Telephone Last Name: First Name: Phone: Place Call Help Help- Type name and place call
437
Throw-away vs. Evolutionary Prototypes
A “quick and dirty” prototype to test an idea or a concept is called a throw-away prototype Throw-away prototypes should not be incorporated into final systems Because it is designed more carefully, an evolutionary prototype can be incorporated into the final system Evolutionary prototypes provide a double benefit, but at a higher cost
438
Evolutionary Development
Evolutionary development divides the design process into architectural design – High level design General structure and responsibilities primary classes and interaction detailed design specific classes, methods, and algorithms This allows us to create refinement cycles Each refinement cycle focuses on one aspect of the system As each refinement cycle is addressed, the system evolves
439
An Evolutionary Development Model
Establish refinement scope System test Establish requirements Architectural design Unit and integration test Identify classes & objects Implementation Identify relationships Detailed design
440
Refinement Cycle: #1 Establish the Scope
First, we establish the refinement scope to define the specific nature of the next refinement For example: Create part of the user interface for the program Test the feasibility of a particular requirement Develop utility classes for general program support Object-oriented programming is well suited to this approach Choosing the most appropriate next refinement is important and requires experience
441
Refinement Cycle: #2 Identify relevant classes/objects
Identify classes and objects that relate to the current refinement Look at the nouns in the requirements document Candidates categories include physical objects (books, balls, etc.) People (student, clerk, professor, etc.) Places (room, airport, etc.) Containers (bookcase, transaction list, etc.) Occurrences (sale, meeting, accident, etc.) Information stores (catalog, event log) Categories may overlap Consider reusing existing classes Is Student Class enough? What about Grad. & Under Grad?
442
Refinement Cycle: #3 Identify relationships
Identify relationships among classes general association (“uses”) aggregation (“has-a”) inheritance (“is-a”) Associated objects use each other for the services they provide Aggregation, also called composition, permits one object to become part of another object Cardinality describes the numeric relationship between the objects For example, a car might have four wheels associated with it
443
Refinement Cycle: #3 (cont.) Inheritance
Inheritance, discussed in detail in Chapter 7, may lead to the creation of a new “parent” abstract class whose sole purpose is to gather common data and common methods in one place Use UML class diagrams to show the relationships
444
Refinement Cycle: #3 (cont.)
Person # age : int + toString () : String Inheritance Association StudentBody + main (args : String[]) : void + toString() : String 1 2 Student - firstName : String - lastName : String - homeAddress : Address - schoolAddress : Address - streetAddress : String - city : String - state : String - zipCode : long Address Aggregation
445
Refinement Cycle: #4-6Detailed design, implement and test
Finally, a refinement cycle includes detailed design, implementation, and testing All the members of each class need to be defined Each class must be implemented (coded) Stubs sometimes are created to permit the refinement code to be tested A unit test focuses on one particular component, such as a method or a class An integration test focuses on the interaction between components
446
Specification of code Specification of design details
Invariant: collection of facts which are true Precondition/Postcondition Preconditions: Conditions which are required for code to execute correctly Postconditions: Correct changes which result after code has been executed
447
Specification of code:An Example (AlarmClock class)
Invariant An Alarmclock object Keeps track of a single alarm time in terms of time and minutes Cannot distinguish between AM and PM times Has attribute values restricted to the following ranges: 1 <= hour <= 12 and 0 <= minutes <= 59 Update Methods public void advanceOneHour() precondition hour < 12 modifies hour postcondition The value of hour is one unit larger than before
448
Specification of code: An Example (AlarmClock class)
Update Methods (cont…) public void advanceTenMinutes() precondition minute < 50 modifies minute postcondition The value of minute is 10 units higher than before We can use formal logic to express the invariant, pre/post conditions We can then use formal logic to prove that a piece of code is “True”. Source: “The object of Java”, David D Riley, Addison-Wesley, 2002
449
Obtaining the requirements: The PaintBox project
TASK (High level): Create a program which allows the user to draw various shapes and sizes on the screen How will we go about accomplishing this?
450
The PaintBox project: Requirements
Create a mouse driven GUI Allow user to draw lines, circles, ovals, rectangles and squares Allow user to change drawing color Allow user to fill a shape, except a line, with a color. Allow user to being new drawing Allow user to create polylines
451
The PaintBox Project:Initial Refinement steps
create the basic user interface allow the user to draw and fill shapes and to change color allow the user to select, to move, and to modify shapes allow the user to cut, copy, and paste shapes allow the user to save and to reload drawings allow the user to begin a new drawing at any time
452
The PaintBox Project: The Basic User Interface
File Edit Select Line Oval Rect Color Drawing Area
453
The PaintBox Project Discussions with the client lead to additional requirements which are integrated into the requirements document Next the architectural design is prepared Refinement steps are determined #1: the basic user interface #2: drawing basic shapes using different stroke colors #3: cutting, copying, and pasting shapes #4: selecting, moving, and filling shapes #5: modifying the dimensions of shapes #6: saving and reloading drawings #7: final touches such as the splash screen
454
Remaining PaintBox Refinements
The full implementation can be downloaded for the Book’s Website See 10.4 of the text book
455
Obtaining user requirements: The “toughest part”
“Knowledge acquisition bottleneck”: Difficulty to extract information from humans Different personality types: Levels of detail, concepts, thinking holistic, etc. Myers Briggs (16 types), amongst others Processing data and information: concrete versus abstract Decision making: logical and objective versus value related and subjective Introvert versus extravert: stimuli from outside or inside Judgment: random versus “open-ended” See WWW for tests and for sceptics!!!!
456
Summary: Chapter 10 Chapter 10 has focused on:
software development models the software life cycle and its implications linear vs. iterative development approaches goals and techniques of testing an evolutionary approach to object-oriented development
457
Thank You! Ευχαριστώ Dankie WAD MAHAD SAN TAHAY GADDA GUEY
458
Abdulmotaleb El Saddik University of Ottawa
CSI 1102 Abdulmotaleb El Saddik University of Ottawa School of Information Technology and Engineering (SITE) Multimedia Communications Research Laboratory (MCRLab) Distributed Collaborative Virtual Environments (DISCOVER) mcrlab.uottawa.ca
459
Presentation slides for Introduction to Software Design
Chapter 11: Recursion Presentation slides for Introduction to Software Design
460
Midterm Average Group AA = 12.04 Group AB = 12.79 Average = 12.4
461
Recursion Recursion is a fundamental programming technique that can provide elegant solutions certain kinds of problems Chapter 11 focuses on: thinking in a recursive manner programming in a recursive manner the correct use of recursion examples using recursion
462
Recursive Thinking Up to know we saw methods that call other methods to accomplish a goal. Recursion is a programming technique in which a method can call itself to solve a problem A recursive definition is one which uses the word or concept being defined in the definition itself; when defining an English word, a recursive definition usually is not helpful Decoration: any ornament or adornment that decorates something
463
Recursive Thinking But in other situations, a recursive definition can be an appropriate way to express a concept Before applying recursion to programming, it is best to practice thinking recursively
464
Recursive Definitions
Consider the following list of numbers: 24, 88, 40, 37 A list can be defined recursively A LIST is a: number or a: number comma LIST That is, a LIST is defined to be a single number, or a number followed by a comma followed by a LIST The concept of a LIST is used to define itself
465
Recursive Definitions
The recursive part of the LIST definition is used several times, ultimately terminating with the non-recursive part: number comma LIST , 88, 40, 37 , 40, 37 , 37 number 37 The last element in the list is always defined by the non-recursive part of the definition
466
Infinite Recursion All recursive definitions must have a non-recursive part If they don't, there is no way to terminate the recursive path A definition without a non-recursive part causes infinite recursion This problem is similar to an infinite loop with the definition itself causing the infinite “loop” The non-recursive part often is called the base case
467
Recursive Definitions
Mathematical formulas often are expressed recursively N!, for any positive integer N, is defined to be the product of all integers between 1 and N inclusive This definition can be expressed recursively as: 1! = 1 N! = N * (N-1)! (N > 1) The concept of the factorial is defined in terms of another factorial until the base case of 1! is reached
468
Recursive Definitions
5! 5 * 4! 4 * 3! 3 * 2! 2 * 1! 1 2 6 24 120
469
Recursive Programming
A method in Java can invoke itself; if set up that way, it is called a recursive method The code of a recursive method must be structured to handle both the base case and the recursive case Each call to the method sets up a new execution environment, with new parameters and new local variables As always, when the method execution completes, control returns to the method that invoked it (which may be an earlier invocation of itself)
470
Recursive Programming
Consider the problem of computing the sum of all the numbers between 1 and any positive integer N, inclusive This problem can be expressed recursively as: i = 1 N N-1 N-2 = N + = N + (N-1) + = etc. i i i
471
Recursive Programming
public int sum (int num) { int result; if (num == 1) result = 1; else result = num + sum (num - 1); return result; } One branch represent the Base case If-else statement The other branch represent the Recursive part
472
Recursive Programming
main sum sum(3) sum(1) sum(2) result = 1 result = 3 result = 6
473
Recursion vs. Iteration
Just because we can use recursion to solve a problem, doesn't mean we should For instance, we usually would not use recursion to solve the sum of 1 to N problem, because the iterative version is easier to understand; in fact, there is a formula which is superior to both recursion and iteration! You must be able to determine when recursion is the correct technique to use
474
Recursion vs. Iteration
Every recursive solution has a corresponding iterative solution For example, the sum (or the product) of the numbers between 1 and any positive integer N can be calculated with a for loop Recursion has the overhead of multiple method invocations Nevertheless, recursive solutions often are more simple and elegant than iterative solutions
475
Recursion vs. Iteration Programming
public int sum (int num) { int result = 0; for (int number = 1; number <= num; number ++) result += number return result; }
476
Indirect Recursion A method invoking itself is considered to be direct recursion A method could invoke another method, which invokes another, etc., until eventually the original method is invoked again For example, method m1 could invoke m2, which invokes m3, which in turn invokes m1 again until a base case is reached This is called indirect recursion, and requires all the same care as direct recursion It is often more difficult to trace and debug
477
Indirect Recursion m1 m2 m3
478
Towers of Hanoi The Towers of Hanoi is a puzzle made up of three vertical pegs and several disks that slide on the pegs The disks are of varying size, initially placed on one peg with the largest disk on the bottom with increasingly smaller disks on top The goal is to move all of the disks from one peg to another according to the following rules: We can move only one disk at a time We cannot place a larger disk on top of a smaller disk All disks must be on some peg except for the disk in transit between pegs
479
Towers of Hanoi
480
Towers of Hanoi To move a stack of N disks from the original peg to the destination peg move the topmost N - 1 disks from the original peg to the extra peg move the largest disk from the original peg to the destination peg move the N-1 disks from the extra peg to the destination peg The base case occurs when a “stack” consists of only one disk This recursive solution is simple and elegant even though the number of move increases exponentially as the number of disks increases The iterative solution to the Towers of Hanoi is much more complex
481
Towers of Hanoi See SolveTowers.java (page xxx)
See TowersOfHanoi.java (page xxx)
482
Summary Chapter 11 has focused on: thinking in a recursive manner
programming in a recursive manner the correct use of recursion examples using recursion
483
Thank You! Ευχαριστώ Dankie WAD MAHAD SAN TAHAY GADDA GUEY
484
Abdulmotaleb El Saddik University of Ottawa
CSI 1102 Abdulmotaleb El Saddik University of Ottawa School of Information Technology and Engineering (SITE) Multimedia Communications Research Laboratory (MCRLab) Distributed Collaborative Virtual Environments (DISCOVER) mcrlab.uottawa.ca
485
Chapter 12: Data Structures Up to page 650
Presentation slides for Introduction to Software Design
486
Learning objective: Data Structures
Some convenient techniques for organizing and managing information Understand what the following entails: Collections in Java Abstract Data Types (ADTs) Dynamic structures and linked lists Linear data structures: queues and stacks
487
What is a Collection? A collection is an object that serves as a repository for other objects, e.g. collection of students, CD, magazines, food A collection usually provides services such as adding, removing, and otherwise managing the elements it contains Sometimes the elements in a collection are ordered, sometimes they are not Sometimes collections are homogeneous, sometimes the are heterogeneous
488
Abstract Data Types: Implementing a collection
An abstract data type (ADT) is an organized collection of information and a set of operations used to manage that information ADT has: A name Domain of values Set of operations that can be performed Our data structures is considered abstract in order: To hide unneeded details To separate the interface of the structure from its underlying implementation This helps manage complexity and makes it possible to change the implementation without changing the interface
489
ADT Objects are a perfect programming mechanism to create ADTs:
because their internal details are encapsulated We implement an ADT using a dynamic data structure A dynamic data structure grows and shrinks at execution time as required by its contents A dynamic data structure is implemented using links
490
Question Is an ArrayList a dynamic data structure?
Is it homogeneous, or heterogeneous? It represents a dynamic data structure. It heterogeneous: It could contains objects of various types It stores objects references Stores any object because of inheritance and polymorphism
491
Object References: Used for ADTs
Recall that an object reference is a variable that stores the address of an object A reference also can be called a pointer References often are depicted graphically: student John Smith 40725 3.58 Student john = new Student(“John Smith…”);
492
Object References as Links
Suppose a Student class contains a reference to another Student object John Smith 40725 3.57 Jane Jones 58821 3.72 class Student { STRecord info; // info about the student Student next; // link to another Student object } Student john = new Student(“John Smith…”, …); Student jane = new Student(“Jane Jones”, …); john.next = jane;
493
References as Links: The Linked List
References can be used to create a variety of linked structures, such as a linked list: studentList
494
The content of the Intermediate Nodes
The objects being stored should not be concerned with the details of the data structure in which they may be stored For example, the Student class should not have to store a link to the next Student object in the list Instead, we can use a separate node class with two parts: 1) a reference to an independent object and 2) a link to the next node in the list The internal representation becomes a linked list of nodes
495
An example: A Magazine Collection
Let’s explore an example of a collection of Magazine objects The collection is managed by the MagazineList class, which has an private inner class called MagazineNode Because the MagazineNode is private to MagazineList, the MagazineList methods can directly access MagazineNode data without violating encapsulation info next
496
MagazineRack.java public class MagazineRack { // Creates a MagazineList object, adds several magazines to the // list, then prints it. public static void main (String[] args) { MagazineList rack = new MagazineList(); rack.add (new Magazine("Time")); rack.add (new Magazine("Woodworking Today")); rack.add (new Magazine("Communications of the ACM")); rack.add (new Magazine("House and Garden")); rack.add (new Magazine("GQ")); System.out.println (rack); } }
497
MagazineList.java public class MagazineList { private MagazineNode list; // Sets up an initially empty list of magazines. MagazineList() { list = null; } Continued….
498
MagazineList.java // Creates a new MagazineNode object and adds it to the end of the linked list. public void add (Magazine mag) { MagazineNode node = new MagazineNode (mag); MagazineNode current; if (list == null) list = node; else { current = list; // we are at the list’s beginning while (current.next != null) // walk through the list to the end current = current.next; current.next = node; } }
499
MagazineList.java // Returns this list of magazines as a string.
public String toString () { String result = ""; MagazineNode current = list; while (current != null) { result += current.magazine + "\n"; current = current.next; } return result; } Continued….
500
MagazineList.java public class MagazineList // An inner class that represents a node in the magazine list. // The public variables are accessed by the MagazineList class. private class MagazineNode { public Magazine magazine; public MagazineNode next; // // Sets up the node // public MagazineNode (Magazine mag) { magazine = mag; next = null; } } }
501
Magazine.java public class Magazine { private String title; // // Sets up the new magazine with its title. // public Magazine (String newTitle) { title = newTitle; } // // Returns this magazine as a string. // public String toString () { return title; } }
502
Magazine Collection A method called insert could be defined to add a node anywhere in the list, to keep it sorted, for example info next info next info next newnode info next
503
Magazine Collection A method called delete could be defined to remove a node from the list info next
504
Other Dynamic List Representations
It may be convenient to implement as list as a doubly linked list, with next and previous references list
505
Other Dynamic List Implementations
It may be convenient to use a separate header node, with a count and references to both the front and rear of the list count: 4 front rear list
506
Other Dynamic List Implementations
A linked list can be circularly linked in which case the last node in the list points to the first node in the list If the linked list is doubly linked, the first node in the list also points to the last node in the list Choice of linking: The representation should facilitate the intended operations and make them easy to implement
507
Other Classic Data Structures
Classic linear data structures include queues and stacks Classic nonlinear data structures include trees, binary trees, graphs, and digraphs CSI2114 explores Data Structures in much more detail Introduction to abstract data types. Trees, binary search trees, balanced trees. Searching. Sorting. Simple examples of complexity analysis. Graphs, simple graph algorithms: depth-first and breadth-first search, minimum spanning tree, shortest path. (Lab work will be done in the Java programming language). Prerequisite: CSI1101 or CSI1102
508
Linear data structure 2: Queues
A queue is similar to a list but adds items only to the rear of the list and removes them only from the front It is called a FIFO data structure: First-In, First-Out Analogy: a line of people at a bank teller’s window Used quite a lot in Operation Systems Queues often are helpful in simulations or any situation in which items get “backed up” while awaiting processing enqueue dequeue
509
More about Queues We can define the operations for a queue
enqueue - add an item to the rear of the queue dequeue (or serve) - remove an item from the front of the queue empty - returns true if the queue is empty A queue can be represented by a singly-linked list; it is most efficient if the references point from the front toward the rear of the queue
510
Linear data structure 2: Stacks
A stack ADT is also linear, like a list or a queue Items are added and removed from only one end of a stack It is therefore LIFO: Last-In, First-Out Analogies: a stack of plates in a cupboard, a stack of bills to be paid, or a stack of hay bales in a barn pop push
511
More about Stacks Some stack operations:
push - add an item to the top of the stack pop - remove an item from the top of the stack peek (or top) - retrieves the top item without removing it empty - returns true if the stack is empty The java.util package contains a Stack class See Decode.java (page 649)
512
Decode.java import java.util.Stack; import cs1.Keyboard;
public class Decode { // Decodes a message by reversing each word in a string. public static void main (String[] args) { Stack word = new Stack(); String message; int index = 0; System.out.println ("Enter the coded message:"); message = Keyboard.readString(); System.out.println ("The decoded message is:"); Continued…
513
Decode.java (cont) Enter the coded message:
while (index < message.length()) { // Push word onto stack while (index < message.length() && message.charAt(index) != ' ') { word.push (new Character(message.charAt(index))); index++; } // Print word in reverse while (!word.empty()) System.out.print (((Character)word.pop()).charValue()); System.out.print (" "); index++; } System.out.println(); } } Enter the coded message: Hello world The decoded message is: olleH dlrow
514
Data structures in Java: Collection Classes
The Java standard library contains several classes that represent collections, often referred to as the Java Collections API Their underlying implementation is implied in the class names such as ArrayList and LinkedList Several interfaces are used to define operations on the collections, such as List, Set, SortedSet, Map, and SortedMap
515
Summary: Chapter 12 Understand what the following entails:
Collections in Java Abstract Data Types (ADTs) Dynamic structures and linked lists Linear data structures: queues and stacks Remember about CSI2114!!!
516
Thank You! Ευχαριστώ Dankie WAD MAHAD SAN TAHAY GADDA GUEY
Similar presentations
© 2024 SlidePlayer.com Inc.
All rights reserved.