Transcript Chapter X
An Introduction to
Programming and Object
Oriented Design using Java
2nd Edition. May 2004
Jaime Niño
Frederick Hosch
Chapter 1: Data Abstraction. Introductory concepts.
Objectives
After studying this chapter you should understand the
following:
the nature of a software object – its properties, functionality, data, and
state;
the notions of query and command;
values and collection of values called types;
Java’s built-in types;
variables, and the relationship between values, variables, and types;
classes as collections of related objects;
the syntactic layout of a class as defined in Java;
reference values and reference types.
May 2004
NH-Chapter X
1
Objectives
Also, you should be able to:
classify an object as immutable or mutable;
describe the components of a system developed using objects;
describe the values comprising the built-in Java types;
describe literals of the built-in Java types;
form legal Java identifiers and name the role of identifiers in
programming.
May 2004
NH-Chapter X
2
Objects
Fundamental abstractions to build software systems.
Objects are often abstractions of real-world entities:
students,
employees,
rooms,
passageways,
chess pieces.
May 2004
NH-Chapter X
3
Where do objects come from?
From the problem statement
Analyze the problem to identify objects
May 2004
NH-Chapter X
4
Objects
System functionality: set of tasks it must perform.
Tasks system must perform are allocated to objects.
A given object has responsibility for performing certain
specific tasks of the system.
A critical part of system design is allocating
responsibilities to objects.
May 2004
NH-Chapter X
5
Data and State
An object is responsible for maintaining relevant data
about the thing it models.
Example: Given object Student as part of a
registration system. Data it maintains:
Name,
address,
number of credit hours the student is enrolled in,
student’s course schedule,
whether or not the student has paid fees, etc.
May 2004
NH-Chapter X
6
Data and State
An object contains a number of data items,
Each data item consists of
a data description
an associated value.
May 2004
NH-Chapter X
7
Data and State
The data descriptions are the properties of the object.
Example: Properties of a student object include
Name,
address,
number of credit hours the student is enrolled in,
student’s course schedule,
whether or not the student has paid fees, etc.
If we are modeling a playing card, object properties
will include suit and rank.
May 2004
NH-Chapter X
8
Data and State
Each property of an object has an associated
value.
Examples:
The student’s name is Stephen Dadelus,
the playing card’s rank is Jack,
the window’s width is 100 pixels.
May 2004
NH-Chapter X
9
Data and State
Instance variables: variables for object’s values.
A portion of computer memory reserved for storing a
particular value.
Memory space used to store an object’s instance
variables allocated to object when created.
An instance variable is allocated for each property of
the object.
Instance variable contains the data value associated
with that property.
May 2004
NH-Chapter X
10
Data and State
The set of properties of an object is fixed.
The associated values can often change over time:
a student can change address or even name;
a computer user can change the width and height of a
window on the screen.
Object’s state: set of object’s instance variables
and associated values at any given time.
May 2004
NH-Chapter X
11
Mutable and Immutable objects
Immutable object: object whose state cannot be
changed.
An object whose state can be changed is mutable.
May 2004
NH-Chapter X
12
Mutable and Immutable objects
Example of mutable objects:
Student,
Computer screen window
Examples of immutable objects:
A playing card
A Calendar date
A color.
May 2004
NH-Chapter X
13
Functionality: Queries and Commands
An object maintains data in order to support its
functionality.
Object functionality: actions the object performs in
response to requests from other objects.
May 2004
NH-Chapter X
14
Functionality: Queries and Commands
Two kinds of requests an object can serve:
Query: request for data
Command: request to change its state.
Object’s features:
commands.
collection
May 2004
NH-Chapter X
of
queries
and
15
Queries
A request for data maintained by the object.
Object responds by providing a value.
May 2004
NH-Chapter X
16
Queries
Examples:
a student object might be queried for the student’s name,
a playing card object for the card’s suit,
a chess piece for its position.
Queries are used to gather information about an
object’s state.
May 2004
NH-Chapter X
17
Queries
An object might support queries for data it does not
explicitly store.
Example: object modeling a window maintains
length and width. Design query for the window’s
area.
Area is not explicitly stored in an object’s instance
variables.
May 2004
NH-Chapter X
18
Queries
An object might not support queries for data it does
store.
Example: an object representing a computer user
contains the user’s name and password.
The object is not likely to support a query for the
password.
May 2004
NH-Chapter X
19
Commands
Instructs object to perform some action resulting in
value stored in one or more of the object’s instance
variables to be changed.
May 2004
NH-Chapter X
20
Commands
Examples:
a student object might be instructed to drop a course,
changing the credit hours and course schedule properties of
the object;
a chess piece might be told to move to a different square;
or a solitaire playing card object might be instructed to
turn over, changing its “is face up” property.
May 2004
NH-Chapter X
21
Commands
An immutable object supports no commands to
change its state.
May 2004
NH-Chapter X
22
Objects change in response to commands
Student
Student
name
address
name
R. Raskolnikov
S. Place, Petersburg
socialSecurityNumber
address S. Place, Petersburg
000-00-0001
creditHours
9
feesPaid
no
courseSchedule
drop course
(Ethics 1001)
socialSecurityNumber
000-00-0001
creditHours
6
feesPaid
no
courseSchedule
Law 6592
Ethics 1001
Law 6592
Comp Sci 1583
Comp Sci 1583
SolitairePlayingCard
suit Heart
rank
SolitairePlayingCard
turnOver
10
state before command
suit Heart
rank
isFaceUp true
May 2004
R. Raskolnikov
10
isFaceUp false
command
NH-Chapter X
state after command
23
Values and Types
Values: abstractions used to represent, or model,
properties of objects.
May 2004
NH-Chapter X
24
Values and Types
Integers model problem features we count:
the number of students in a class, or
the number of words on a page.
Real numbers model problem features we measure:
the width of a table,
the voltage drop across a line.
May 2004
NH-Chapter X
25
Values and Types
Values are grouped together according to the
operations we perform with them.
Type: A set of values along with the operations that
can be performed with them.
May 2004
NH-Chapter X
26
Java’s built-in primitive types
Integer types:
byte, short, int, long.
Real types:
float, double.
The operations for these types include:
addition, subtraction, multiplication, and division.
May 2004
NH-Chapter X
27
Java’s built-in primitive types
char:
values include the upper and lower case letters, digits,
punctuation marks, and spaces that constitute text.
boolean.
contains only the two values true and false.
May 2004
NH-Chapter X
28
Ranges of integer type values
type
Smallest value
Largest value
byte
-128
short
-32,768
32,767
int
-2,147,483,648
2,147,483,647
long
May 2004
127
-9,223,372,036,854,775,808 9,223,372,036,854,775,807
NH-Chapter X
29
Types and variables
A variable can contain values of only one type.
An int variable contains a single int value;
a double variable contains a double value, etc.
May 2004
NH-Chapter X
30
Types and variables
The type of value a variable contains is
“type of the variable” and
fixed when the object is designed.
Example: The width of a window might be 100
pixels at one time, and 150 pixels some time later.
Value will always be an integer, and instance variable
modeling it is of type int
May 2004
NH-Chapter X
31
Classes
Class: collection of similar objects, that is, objects
supporting the same queries and commands.
Every object is an instance of some class, which
determines the object’s features.
May 2004
NH-Chapter X
32
Example: A class modeling a counter
/**
* A simple integer counter.
*/
public class Counter {
1
/**
2
* Increment the count by
1.
*/
public void incrementCount
() {
count = count + 1;
}
private int count;
/**
* Create a new Counter, with
* the count initialized to 0
*/
public Counter () {
count = 0;
}
/**
* The number of items counted
*/
public int currentCount () {
return count;
}
May 2004
/**
* Reset the count to 0.
*/
public void reset () {
count = 0;
}
} // end of class Counter
NH-Chapter X
33
Reference values:
Objects as properties of objects
Know how to model object’s properties such as
numbers, or characters.
How to model properties like the name, address, and
course schedule or birthday of a student?
May 2004
NH-Chapter X
34
Reference values:
Objects as properties of objects
Example: to model birthday, we first model a date
with an object, via the class Date:
Date
May 2004
int month
2
int day
2
i nt year
1982
NH-Chapter X
35
Reference values
The student’s value for property “birthday” denotes or refers
to a Date object.
Value is a reference value.
Type is reference-to-Date
reference value: a value that denotes an object.
Student
…
Date
intmonth 2
Date birthday
intday
…
May 2004
2
intyear 1982
NH-Chapter X
36
Modeling students name, address:
Java’s class String
String instance: immutable object that contains a
sequence of characters.
A String can be queried for length and for individual
characters that comprise it.
Class contains no state-changing commands.
String
value
Student
"R. Raskolnikov"
int length
14
String name
String address
É
String
value
int length
May 2004
NH-Chapter X
"S. Place, Petersburg"
20
37
Overview of a complete system
Set of objects comprising system can be divided into:
Model: objects that cooperate to solve the problem.
external interface: or user interface and
data management: objects that maintain problem’s data.
May 2004
NH-Chapter X
38
Overview of a complete system
Example:
We build a very simple system to test a Counter.
The model : only a single class Counter.
The user interface: only a single class CounterTester.
Data management: none.
May 2004
NH-Chapter X
39
//A simple tester for the class Counter.
public class CounterTester {
private Counter counter;
// Create a new CounterTester.
public CounterTester () {
counter = new Counter();
}
// Run the test.
public void start () {
System.out.println("Starting count:");
System.out.println(counter.currentCount());
counter.incrementCount();
counter.incrementCount();
counter.incrementCount();
System.out.println("After 3 increments:");
System.out.println(counter.currentCount());
counter.reset();
System.out.println("After reset:");
System.out.println(counter.currentCount());
}
}
May 2004
NH-Chapter X
40
Getting it all started
We need one more class containing a method named main, as
shown
/**
* Test the class Counter.
*/
public class Test {
/**
* Run a Counter test.
*/
public static void main (String[] args) {
CounterTester tester = new CounterTester();
tester.start();
}
}
May 2004
NH-Chapter X
41
Running a program
It depends on the computing system and environment used.
We must identify class containing method main to the Java
run-time system. For instance,
$ java Test
Running the program will produce six lines of output:
Starting count:
0
After 3 increments:
3
After reset:
0
May 2004
NH-Chapter X
42
Objects that “wrap” primitive values
Primitive values and objects are different.
For each primitive type Java provides classes
Boolean, Character, Byte, Short,
Integer, Long, Float, Double.
Immutable classes
Wrap a primitive value into an object.
May 2004
NH-Chapter X
43
Objects that “wrap” primitive values
Example: Integer class.
An instance is an immutable object.
It has a single int property.
Value of property given during creation.
Property is accessed via query: intValue()
Integer anInteger = new Integer(2);
int anInt = anInteger.intValue();
Integer
Integer anInteger
int anInt
May 2004
int value
2
2
NH-Chapter X
44
Boxing and unboxing
Automatic and implicit conversion between
primitive values and the wrapper classes.
Integer anInteger = 3;
Implicitely converted to:
Integer anInteger =
May 2004
new Integer(3);
NH-Chapter X
45
Boxing and unboxing
Also,
int anInt = anInteger + 1;
Implicitly converted to:
int anInt = anInteger.intValue() + 1;
May 2004
NH-Chapter X
46
Identifiers
We use identifiers to name things in Java.
A Java identifier is a sequence of characters consisting of
letters, digits, dollar signs($), and/or underscores(_). An
identifier can be of any length, and cannot begin with a digit.
X
b29
b$2
Abc
aVeryLongIdentifier
a2b
A_a_x
$_
$$$
IXLR8
Not legal identifiers.
2BRnot2B
May 2004
a.b
Hello!
NH-Chapter X
A-a
Test.j
47
Identifiers
Java identifiers are case sensitive. This means that
upper and lower case characters are different. For
example, the following are all different identifiers.
total
May 2004
Total TOTAL
NH-Chapter X
tOtAl
48
Identifiers
There are a number of keywords and identifier
literals reserved for special purposes.
Cannot be used as identifiers.
Identifier literals: true, false, null
May 2004
NH-Chapter X
49
Guidelines in choosing identifiers
Use lower-case characters, with upper-case characters inserted
for readability.
Capitalize class names.
Choose descriptive identifiers
Avoid overly long identifiers.
Avoid abbreviations.
Be as specific as possible.
Take particular care to distinguish closely related entities.
Don’t incorporate the name of its syntactic category in the
name of an entity
May 2004
NH-Chapter X
50
Literals
A literal is a representation of a value.
May 2004
NH-Chapter X
51
Integer Literals
Integer literals look like ordinary decimal numbers,
and denote values of the type int.
Integer literals can’t contain commas and shouldn’t
have leading zeros.
25
May 2004
0
1233456 289765
NH-Chapter X
7
52
Floating point Literals
Numbers that include a decimal point denote values
of type double.
0.5 2.67 0.00123 12.0 2.
May 2004
NH-Chapter X
.6
53
Floating point Literals
Exponential notation can also be used for double
literals. The following are legal double literals:
0.5e+3
May 2004
0.5e-3
NH-Chapter X
0.5E3
5e4 2.0E-27
54
Character Literals
Character literals (denoting values of type char)
consist of a single character between apostrophes.
'A' 'a' '2' ';' '.' ' '
May 2004
NH-Chapter X
55
Character Literals
The apostrophe, quotation mark, and backslash must
be preceded by a backslash in a character literal.
'\'' '\"' '\\'
May 2004
NH-Chapter X
56
Character Literals
'\t' //represents the tab character
'\n' //represents the end of line char
May 2004
NH-Chapter X
57
Boolean Literals
The two values of type boolean are written as follows:
true
May 2004
false
NH-Chapter X
58
Boolean Literals
String literal is a possibly empty sequence of
characters enclosed in quotations:
"ABC" "123" "A"
May 2004
NH-Chapter X
""
59
Summary
chapter introduced the fundamental notions of value,
type, object, and class. We also saw Java identifiers
and literals.
May 2004
NH-Chapter X
60
Summary
Values: fundamental pieces of information
manipulated in a program.
Values are grouped along with their operations into
types.
May 2004
NH-Chapter X
61
Summary
Java has two kinds of types:
primitive types:
several integer types (byte, short, int, long);
two real or floating types (float and double);
character type char, and
type boolean which contains two values, true and false.
reference types.
May 2004
NH-Chapter X
62
Summary
A reference value denotes, or refers to, an object.
Objects are the fundamental abstractions from which
software systems are built.
May 2004
NH-Chapter X
63
Summary
Objects are often abstractions of real-world entities,
Designed to support system functionality.
May 2004
NH-Chapter X
64
Summary
An object’s role in the system determines the set of
features the object is responsible for supporting.
These features include
queries, by which data values are obtained from the object;
commands, which cause the object to perform some
actions change state of the object.
May 2004
NH-Chapter X
65
Summary
Instance variables: Data maintained by the object
State of object: Instance variables and their values at
any given point in the computation
Query reports information obtained from the state of
the object.
Command usually causes object to change state.
Some objects are immutable.
state cannot change after the object is created.
May 2004
NH-Chapter X
66
Summary
Objects are grouped into classes.
A class defines the features of, and data items
maintained by, its members.
All objects in a particular class have the same
features.
An object that is a member of a particular class is
called an instance of the class.
May 2004
NH-Chapter X
67
Summary
Defining a class:
define instance variables
define algorithms for carrying out queries and commands.
May 2004
NH-Chapter X
68
Summary
Reference value :value that denotes or refers to the
object.
Type is reference-to-x, where x is the class of the
object.
May 2004
NH-Chapter X
69
Summary
Objects that comprise a system can be divided into
three basic subsystems:
Model: represent the problem and cooperate to provide the
solution.
External interface: user interface.
Data management: responsible for storing and retrieving
persistent data in a file system or data base.
May 2004
NH-Chapter X
70
Summary
identifiers : name of entities in programs.
We name: classes, objects, properties, features
An identifier is a sequence of characters consisting of
letters, digits, dollar signs, and/or underscores.
May 2004
NH-Chapter X
71
Summary
Literal: denote a particular value in a program
Literals can be used to denote
integer values,
floating point values,
character values,
boolean values,
Strings.
May 2004
NH-Chapter X
72