Download Chap08

Document related concepts
no text concepts found
Transcript
Chapter 8
Object-Oriented Software
Engineering
Knowledge Goals
• Understand the concepts of
encapsulation and abstraction
• Know how control and data abstraction
facilitate modifiability and reuse
• Understand the basic principles of
object-oriented design
• Know how packages support
encapsulation
2
Knowledge Goals
• Appreciate the abstraction provided by
the enum type
• Understand how objects collaborate
• Know how to interpret a UML class
diagram
3
Skill Goals
• Declare and use an enum type
• Develop a transformer (mutator) method
• Create a package with multiple compilation
unites
• Write a CRC card for an object
• Conduct scenarios using CRC cards
• Identify collaborations between objects
• Convert a CRC card into a Java class
• Draw a UML class diagram
4
Class Design Principles
Encapsulation
Designing a class so that its attributes are
isolated from the actions of external code except
through the formal interface
Formal interface
The components of a class that are externally
accessible, which consist of its nonprivate fields
and methods
5
Class Design Principles
Failure
to
encapsulate
can
lead
to
chaos
6
Class Design Principles
Reliability
A property of a unit of software such that it
always operates consistently, according to the
specification of its interface
Specification
The written description of the behavior of a class
with respect to its interface
7
Class Design Principles
An encapsulated class is
like a gated community
The iron fence surrounds
(encapsulates) the
houses
The gate is the formal interface
The written instructions for opening the gate are the
specification
8
Class Design Principles
private int month;
private int day;
private int year;
9
public int month;
public int day;
public int year;
Access
through
Direct
access
pulic void setDate
(int aMonth,
int aDay,
int aYear)
Client code can
directly access
month, day, year
Class Design Principles
Abstraction is the key to handling complexity
Encapsulation is the basis for abstraction
Abstraction
The separation of the logical properties
(interface and specification) of an object from
its implementation
10
Class Design Principles
Data abstraction
The separation of the logical representation of
an object's attributes from its implementation
11
Class Design Principles
Control abstraction
The separation of the object's behavioral
specification from the implementation of the
specification
public int getDay()behaves the same regardless
of which implementation is used
12
Class Design Principles
Modifiability
The property of an encapsulated class that
allows the implementation to be changed
without having an effect on code that uses it
Implementation
changed
User doesn't even know!
13
Class Design Principles
Reuse
The ability to import and use a class in different
contexts without requiring modifications to either
class or using code
Used in
3 contexts
14
Class Design Principles
Mutate
Changing the value(s) of an object's attributes(s)
after it is created
Transformer (mutator)
A method that changes the value of an object's
attribute
Immutable object
An object for which no transformer methods are
defined
15
Class Design Principles
Constructor-observer classes are always
encapsulated (Why?)
Mutable classes are encapsulated if the
changes are done by methods specified in the
formal interface, not through the use of public
fields
16
Class Design Principles
private int month;
private int day;
private int year;
Access
through
pulic void setDate
(int aMonth,
int aDay,
int aYear)
17
public int month;
public int day;
public int year;
Class Design Principles
Remember
the
difference
?
18
Class Design Principles
Effect of
assigning
a new
value to a
reference
parameter
19
Class Design Principles
Class String is immutable
Oh? What about the concatenation?
String myName = "Susy" + " " + "Sunshine";
Three strings are created and two are discarded
Class StringBuffer is a mutable string class
20
Encapsulation and Abstraction in Java
Compilation unit
A file, named after the one public class it
contains
Package
A named collection of compilation units
Package
Class A
21
Class B
Class C
Encapsulation and Abstraction in Java
Create
package mine;
public class Name
{…}
package mine;
public class Phone
{…}
package mine;
public class Address
{…}
22
Access
import mine.Name;
import mine.Address;
import mine.Phone;
or
import mine.*;
Which is better?
Encapsulation and Abstraction in Java
directory: mine
file: Name.java
file: Phone.java
file: Address.java
Classes in a package can access
one another’s non-private fields
Don't forget to create the directory
and put the classes into it
23
Encapsulation and Abstraction in Java
Up 'til now, we had to read and write objects one
field at a time
Wouldn't it be nice if we could read and write an
object by just giving its name?
Of course, we wouldn't bring it up if there
weren't a way…
24
Encapsulation and Abstraction in Java
Output and Input of Objects
Serializing
Translating an object into a stream of bytes
Deserializing
Translating a serialized stream of bytes back
into an object
Output and Input, shouldn't
that be Input and Output? NO!
25
Encapsulation and Abstraction in Java
We can read an object from a file as a whole
only if it has first been written as a whole from
within a program
public class Name implements Serializable
says that instances of class Name can be written
and read as a whole (i.e. stream of bytes)
How? Don't ask! Just enjoy
26
Encapsulation and Abstraction in Java
import java.io.*;
public class ObjectFileWrite
{
public static void main(String[] args)
throws IOException
{
ObjectOutputStream outObject; outObject =
new ObjectOutputStream(
new FileOutputStream("outObject.dat"));
Name person = new Name("Susy", "Su", "Sunshine");
outObject.writeObject(person);
outObject.close();
}
}
27
Encapsulation and Abstraction in Java
import java.io.*;
public class ObjectFileRead
{
public static void main(String[] args) throws
IOException, ClassNotFoundException
{
ObjectInputStream inObject; inObject =
new ObjectInputStream(
new FileInputStream("outObject.dat"));
//Read Name object and display it
Name person = (Name)inObject.readObject();
System.out.println(person);
inObject.close();
}
}
28
Encapsulation and Abstraction in Java
import java.io.*;
public class ObjectFileRead
{
public static void main(String[] args) throws
IOException, ClassNotFoundException
{
ObjectInputStream inObject; inObject =
new ObjectInputStream(
new FileInputStream("outObject.dat"));
//Read Name object and display it
Name person = (Name)inObject.readObject();
System.out.println(person);
inObject.close();
}
}
29
Encapsulation and Abstraction in Java
public static void main(String[] args) throws
IOException, ClassNotFoundException
{
…
Name person = (Name)inObject.readObject();
System.out.println(person);
…
}
 The object (stream of bytes) must be typecast
back into a Name instance
 class Name must be known to the application
30
Encapsulation and Abstraction in Java
Properties of data types -- an aside
Atomic
Its values have no component parts
Scalar
The values are ordered and each value is atomic
Ordinal
Each value (except the first) has a unique predecessor
and each value (except the last) has a unique successor
Which of these apply to Boolean, integral, and real values?
31
Encapsulation and Abstraction in Java
One more Java feature supporting abstraction
Enumeration
A data type in which the elements are a set of
identifiers that are atomic, scalar, and ordinal
package colorManagement;
enum Spectrum
{
RED, ORANGE, YELLOW, GREEN, BLUE,
INDIGO, VIOLET
}
32
Encapsulation and Abstraction in Java
Examples of use
enum Spectrum {RED, ORANGE, YELLOW, GREEN, BLUE,
INDIGO, VIOLET}
Spectrum color;
// declares a variable
color = Spectrum.GREEN; // sets color to Green
System.out.print(color); // prints "GREEN"
color = Spectrum.valueOf("RED"); // sets color to
// RED
if (color.compareTo(Spectrum.BLUE)) // tests color
for (Spectrum color : Spectrum.values())
System.out.println(color); // prints all values
33
Encapsulation and Abstraction in Java
public static void main(String[] args)
{
Spectrum color;
Scanner in = new Scanner(System.in);
System.out.print("Enter RED, YELLOW, or GREEN: ");
color = Spectrum.valueOf(in.nextLine());
switch (color)
{
case RED: System.out.println("Stop"); break;
case GREEN: System.out.println("Go"); break;
case YELLOW: System.out.println("Changing"); break;
default: System.out.println("Light broken");
}
}
34
Encapsulation and Abstraction in Java
Remember, abstraction is the most powerful tool
people have for managing complexity!
35
Notation for Object-Oriented Design
Object-Oriented design
A technique for developing software in which the
solution is expressed in terms of objects that interact
with one another
Responsibility
An action that an implementation of an object must be
capable of performing
Collaboration
An interaction between objects in which one object
request that another object carry out one if it
responsibilities
Yes, these should sound familiar
36
Notation for Object-Oriented Design
CRC cards (Class Responsibility Collaborations)
CRC cards are a notational device that allows us
to organize our thoughts during the object-oriented
design process
37
Notation for Object-Oriented Design
Stages in the OOD process (from Chapter 1)
 Brainstorm List all objects that might contribute to
solution
 Filter Review the classes to find duplicates or
remove unnecessary objects (create CRC cards)
 Responsibilities Determine the operations
associated with a class of objects
 Collaborations Determine the interactions between
classes
Determining responsibilities and
collaborations needs more refinement
38
Notation for Object-Oriented Design
Responsibilities
 knowledge responsibilities return
information about the state of the object (get
+ field name)
 action responsibilities are operations that
require the object to perform an action
Use scenario walk-throughs, a role playing
technique,
 to explore the actions of a class
 to explore the interactions of classes
39
Notation for Object-Oriented Design
Roleplaying
to
determine
class
interactions
40
Example
Problem: Create an application that allows a
user to edit entries on a file representing an
address book
Identify possible classes
Address Book
Name
Input file
Field
User
Address
Output file
Entry
Phone
Format
How would you filter this list?
41
Example
Filtered list
Address book
User Interface
Entry
Name
Address
Phone
Output File
Field
42
What
about an
input
file
?
Example
CRC cards for Name initial responsibilities
43
Example
Scenario Walkthrough
What happens when the user wants to change
the phone number?




Get an entry (responsibility of UserInterface)
Select field to change
Input new field value
Write updated entry to file
Driver
44
Example
Subsequent Scenarios
What happens when the user
 Wants to change the phone number? (done)






45
Wants to change the name?
Wants to change the address?
Decides not to make any changes?
Wants to change more than one field?
Wants to change only part of a field?
……
Attributes and their Representation
Algorithms for responsibilities work with
attributes, so the next step is to determine
a classes attributes and their internal
representations
(Remember, attributes are fields in an
object not data from our external view)
46
Attributes and their Representation
Class Name: Date
Superclass:
Responsibilities
Subclasses:
Collaborations
Initialize(month, day, year)
Get month returns String
Get day returns int
Get year returns int
What are the attributes?
47
Attributes and their Representation
Two different sets of attributes and their
internal representations for class Date
Can you think of other representations?
48
UML Diagrams
UML diagrams
A collection of symbols used to represent
classes and their interactions
Class diagram for class Phone
Class name
Attributes & types
Method headings
49
UML Diagrams
Collaborates with
Contains
50
UML Diagrams
Can
you
see
all the
relationships
?
51
Extras
I have
a computer
architecture
named after
me; I also
worked on the
atomic bomb
Who am I?
52
Extras - GUI Track
Output from fileChoser.showOpenDialog(null)
53
Extras - GUI Track
JFileChooser fileChooser = new JFilechooser();
int action = fileCooser.showOpenDialog(null);
if (action == JFileChooser.APPROVE_OPTION)
Scanner infile =
new Scanner(fileChooser.getSelectedFile());
else
System.out.println("No file selected");
54