Illinois Institute of Technology
Download
Report
Transcript Illinois Institute of Technology
OOP
Class 2
CS445 - Object Oriented Design and Programming
An Object of class
OPERATIONS
DATA
Set
Increment
Private data:
hrs
8
Write
.
.
.
mins
25
secs
42
Time
CS445 - Object Oriented Design and Programming
Time
Definitions
CS445 - Object Oriented Design and Programming
Definitions
Definitions of object on the Web:
a tangible and visible entity; an entity that can cast a shadow;
"it was full of rackets, balls and other objects"
Definitions of object-oriented on the Web
“object-oriented ... techniques where data carries with itself the
"methods" (also known as "functions") used to handle that data.
An OO programmer, for instance, can write a statement such
as "object.print()" without having to be concerned about what
kind of object will be involved at "run time" or what its printing
method is. Object-oriented code is both more flexible and more
organized, so it is far easier to write, read, and change than
procedural code…”
www.3dartist.com/WP/dempy/help/glossary.htm
“… A style of software development and packaging based on
how real world objects relate to one another. Data and
procedures are combined in objects; objects communicate with
each other via messages; similar objects are grouped together
into classes; data and procedures are inherited through a class
hierarchy…”www.olenick.com/html/glossary.html
CS445 - Object Oriented Design and Programming
Definitions
Definitions of object-oriented design on the Web:
entails transforming the analysis model into a feasible design.
kaykeys.net/science/computerwork/oodesign/
A software design method that models the characteristics of
abstract or real objects using classes and objects.
software.allindiansite.com/java/ojava.html
Object-oriented design (OOD) is a design method in which a
system is modeled as a collection of cooperating objects and
individual objects are treated as instances of a class within a
class hierarchy.
en.wikipedia.org/wiki/Object-oriented_design
CS445 - Object Oriented Design and Programming
Definitions of object-oriented analysis on the Web:
Object-oriented analysis
– builds a model of a system that is composed of objects.
The behavior of the system is achieved through
collaboration between these objects, and the state of the
system is the combined state of all the objects in it.
Collaboration between objects involves them sending
messages to each other.
Definitions of object-oriented programming on the Web:
– “… A programming approach based on the concepts of data
abstraction and inheritance. Unlike procedural programming
techniques, …”
– “… Style of programming characterized by the use of separate
"objects" to perform different tasks within a program. These
"objects" usually consist of an abstract data type or class, along
with the methods used to manipulate that abstract data type …”
– “… A programming methodology built around objects and based
on sending messages back and forth between those objects. The
basic concepts of object-oriented programming are
encapsulation, inheritance, and polymorphism …”
CS445 - Object Oriented Design and Programming
Modeling the Real World
Components of a software system is an interpretation
of the real world
– Model , a representation of parts of the real world
– Algorithm, capture the computation needed to manipulate the
model
Object Orientation is a software development model
that makes use of objects as a representation of the
real world
– An object represents anything in the real world that can be
distinctly identified.
– A class represents a set of objects with similar characteristics
and behavior
CS445 - Object Oriented Design and Programming
History
50’s – 60’s
Focus
Model Used
Algorithm
Computation- Oriented
Control Flow
–solving computation
problems and
–researching efficient
algorithms
70’s – 80’s
Data complexity
Data-Oriented
Data Flow
OO
Balanced view of data
and computation
OO models made of
objects which contain
data and algorithms
CS445 - Object Oriented Design and Programming
Module Structure Chart
Main
Prepare
File for
Reading
Get Data
Print Data
Find
Weighted
Average
Print Heading
CS445 - Object Oriented Design and Programming
Print
Weighted
Average
Two Design Strategies
FUNCTIONAL
DECOMPOSITION
OBJECT-ORIENTED
DESIGN
OBJECT
FUNCTION
FUNCTION
.
.
.
OBJECT
OBJECT
FUNCTION
.
.
.
CS445 - Object Oriented Design and Programming
.
.
.
Software Process Models
CS445 - Object Oriented Design and Programming
Unified Process
a “use-case driven, architecture-centric, iterative
and incremental” software process closely
aligned with the Unified Modeling Language
(UML)
Tools are used to describe customer views (use
cases)
Used mainly for OO based methodologies
Runs in phases
CS445 - Object Oriented Design and Programming
The Unified Process (UP)
Phase 1
Elaborat ion
elaboration
Communication +
Planning
Phase 2
Planning + Modeling
Incept ion
inception
Phase 3
inception
Coding, unit
test & integrate
Components
const ruct ion
result
Release
soft ware increment
t ransit ion
Phase 4 Deployment
product ion
CS445 - Object Oriented Design and Programming
UP Phases
UP Phases
Incept ion
Elaborat ion
Const ruct ion
Transit ion
Workflow s
Requirements
Analysis
Design
Implementation
Test
Support
Iterations
#1
#2
CS445 - Object Oriented Design and Programming
#n-1
#n
Product ion
Incept ion phase
Vision document
Init ial use-case model
Init ial project glossary
Init ial business case
Init ial risk assessment .
Project plan,
phases and it erat ions.
Business model,
if necessary .
One or more prot ot y pes
I nc e pt i o
n
UP Work Products
Elaborat ion phase
Use-case model
Supplement ary requirement s
including non-funct ional
Analy sis model
Soft ware archit ect ure
Descript ion.
Execut able archit ect ural
prot ot y pe.
Preliminary design model
Rev ised risk list
Project plan including
it erat ion plan
adapt ed workflows
milest ones
t echnical work product s
Preliminary user manual
Const ruct ion phase
Design model
Soft ware component s
Int egrat ed soft ware
increment
Test plan and procedure
Test cases
Support document at ion
user manuals
inst allat ion manuals
descript ion of current
increment
CS445 - Object Oriented Design and Programming
Transit ion phase
Deliv ered soft ware increment
Bet a t est report s
General user feedback
Agile Development
CS445 - Object Oriented Design and Programming
The Manifesto for
Agile Software
Development
“We are uncovering better ways of developing
software by doing it and helping others do it.
Through this work we have come to value:
•Individuals and interactions over processes and
tools
•Working software over comprehensive
documentation
•Customer collaboration over contract
negotiation
•Responding to change over following a plan
That is, while there is value in the items on the right,
we value the items on the left more.”
Kent Beck et al
CS445 - Object Oriented Design and Programming
What is “Agility”?
Effective (rapid and adaptive) response to
change
Effective communication among all
stakeholders
Drawing the customer onto the team
Organizing a team so that it is in control of
the work performed
Yielding …
Rapid, incremental delivery of software
CS445 - Object Oriented Design and Programming
An Agile Process
Is driven by customer descriptions of what
is required (scenarios)
Recognizes that plans are short-lived
Develops software iteratively with a heavy
emphasis on construction activities
Delivers multiple ‘software increments’
Adapts as changes occur
CS445 - Object Oriented Design and Programming
Extreme Programming (XP)
The most widely used agile process, originally
proposed by Kent Beck
XP Planning
–
–
–
–
–
Begins with the creation of “user stories”
Agile team assesses each story and assigns a cost
Stories are grouped to for a deliverable increment
A commitment is made on delivery date
After the first increment “project velocity” is used to
help define subsequent delivery dates for other
increments
CS445 - Object Oriented Design and Programming
Extreme Programming (XP)
XP Design
–
–
–
–
XP Coding
–
–
Follows the KIS principle
Encourage the use of CRC cards (see Chapter 8)
For difficult design problems, suggests the creation of “spike solutions”—
a design prototype
Encourages “refactoring”—an iterative refinement of the internal program
design
Recommends the construction of a unit test for a store before coding
commences
Encourages “pair programming”
XP Testing
–
–
All unit tests are executed daily
“Acceptance tests” are defined by the customer and executed to assess
customer visible functionality
CS445 - Object Oriented Design and Programming
Extreme Programming (XP)
simple design
CRC cards
spike solut ions
prot ot ypes
user st ories
values
accept ance t est crit eria
it erat ion plan
refact oring
pair
programming
Release
sof t ware increment
project velocit y comput ed
unit t est
cont inuous int egrat ion
accept ance t est ing
CS445 - Object Oriented Design and Programming
OO Design & Programming
Java Basics
CS445 - Object Oriented Design and Programming
Classes and Objects
Class Point {
An object:
Int x, y;
point1
Attributes or fields:
int x, y;
A method:
Public void move (intd dx,
int dy) {
x +=dx;
y +=dy;
}
}
void move(int dx, int dy)
A message:
point1.move(10, 10)
CS445 - Object Oriented Design and Programming
An Object of class
OPERATIONS
DATA
Time
Modularity
Abstraction
Set
Increment
Encapsulation
Private data:
hrs
8
Polymorphism
Write
.
.
.
Inheritance
mins
25
secs
42
Message Passing
Time
CS445 - Object Oriented Design and Programming
Developing a Java Application
1.
Write the source code
•
•
2.
Using an Integrated Development Environment
(IDE) or text editor
Save in a .java file
Compile the source code:
•
3.
javac ClassName.java
Creates .class file
Execute the application:
•
java ClassName
Run by the Java Virtual Machine (JVM)
CS445 - Object Oriented Design and Programming
A First Application
1
2
3
4
5
6
7
8
9
10
11
12
// First program in Java
// FirstProgram.java
public class FirstProgram
{
public static void main( String [] args )
{
System.out.println( "Programming is not "
+ " a spectator sport!" );
System.exit( 0 );
}
}
CS445 - Object Oriented Design and Programming
Class: FirstProgram
Method: main(...)
Statement: System.out.println(...)
Comments:
–
// a comment
–
/* another comment */
Source file: FirstProgram.java
CS445 - Object Oriented Design and Programming
Program Errors
Compiler errors
– Found by the compiler.
– Usually caused by incorrect syntax or spelling
Run-time errors
– Reported by the JVM
– Usually caused by incorrect use of prewritten
classes or invalid data
Logic errors
– Found by testing the program
– Incorrect program design or incorrect execution of
the design
CS445 - Object Oriented Design and Programming
Program Life Cycle
Source Program
Compile
Library routines
Edit
Link
Other object files
Think
Load
Execute
CS445 - Object Oriented Design and Programming
Introduction: Java Platform
JavaTM platform is based on the idea that the
same software should run on many different
kinds of computers, consumer gadgets, and
other devices.
Portability
– Java platform allows you to run the same Java
application on lots of different kinds of computers.
CS445 - Object Oriented Design and Programming
JVM
Java virtual machine or "JVMTM”
– a translator that turns general Java
platform instructions into tailored
commands that make the devices do
their work
CS445 - Object Oriented Design and Programming
Java Program Phases
1.
Edit
–
2.
Compile
–
3.
Class Loader
Verify
–
5.
javac
Load
–
4.
IDE, vi, emacs, notepad
Verifier (Security and Validation)
Execute
–
Java Interpreter (java or appletviewer)
CS445 - Object Oriented Design and Programming
The java Compiler
javac
– Creates bytecodes
– Stored on disk as .class
– Each file contains bytecode for one and
only one class
CS445 - Object Oriented Design and Programming
The java Class Loader
Loads bytecodes in memory
– Loads .class files from disk into memory
CS445 - Object Oriented Design and Programming
The java Bytecode Verifier
Confirms that all bytecodes are:
– Valid and
– Don't violate Java’s Security restrictions
Works on bytecodes from memory
CS445 - Object Oriented Design and Programming
The java Interpreter
Reads bytecodes and translate them into a
language that is relevant to the targeted
computer architecture
– PC
– Machintosh
– Cell Phone
For applets execution its built into the browser
or the appletviewer
CS445 - Object Oriented Design and Programming
Your first program: HelloWorldApp.java
Displays the greeting "Hello world!". To
create this program, you will:
Create a source file
– A source file contains text, written in Java.
Compile the source file into a bytecode file.
– The compiler, javac, converts these instructions
into a bytecode file
CS445 - Object Oriented Design and Programming
Your first program: HelloWorldApp
Run the program contained in the bytecode file
– The Java interpreter implements the Java VM
– This interpreter takes your bytecode file and carries out
the instructions by translating them into instructions that
your computer can understand.
CS445 - Object Oriented Design and Programming
JRE
CS445 - Object Oriented Design and Programming
JAVA Program
public class HelloWorldApp {
public static void main(String[] args)
{
System.out.println("Hello
World");
}
}
CS445 - Object Oriented Design and Programming
Steps
1.
2.
Save the file as HellowWordApp.java
Compile
–
3.
Javac HellowWordApp.java
HellowWordApp.class
Run the program
–
Java HellowWordApp
CS445 - Object Oriented Design and Programming
Output
CS445 - Object Oriented Design and Programming
What Can be a Class?
Physical Objects – equipments, devices,
products
People – Students, Faculty, Customers
Organizations – Universities, Companies,
Departments, Bank
Places – Buildings, Rooms, Seats
Events – Mouse click, order request, purchase
orders
Concepts – Transaction
The domain determines the classes
CS445 - Object Oriented Design and Programming
What Features Should a Class Have?
Actions should be modeled as methods of a
class
Verb phrases
Underline the verbs and nouns in the description
of the requirements and use cases
Nouns are candidate classes or attributes
Verbs are candidate methods
CS445 - Object Oriented Design and Programming
Java Programming Language
Java Basics
OO Basics
UML Basics
CS445 - Object Oriented Design and Programming
Data Types, Variables, and
Constants
We use Symbolic Names to refer to data
We must assign a data type for very identifier (symbolic
name)
Declaring Variables
Primitive Data Types
Initial Values and Literals
String Literals and Escape Sequences
Constants
CS445 - Object Oriented Design and Programming
Data Types
For all data, assign a name (identifier) and a
data type
Data type tells compiler:
– How much memory to allocate
– Format in which to store data
– Types of operations you will perform on data
Compiler monitors use of data
– Java is a "strongly typed" language
Java "primitive data types"
byte, short, int, long, float, double, char, boolean
CS445 - Object Oriented Design and Programming
Declaring Variables
Every Variable must be given a name and a
data type
Variables hold one value at a time, but that
value can change
Syntax:
dataType identifier;
or
dataType identifier1, identifier2, …;
Naming convention for variable names:
– first letter is lowercase
– embedded words begin with uppercase letter
CS445 - Object Oriented Design and Programming
Java Primitive Data Types
byte, short, int, long , float, double, char,
boolean
primitive
integral
byte char
short
boolean
int
floating point
long
CS445 - Object Oriented Design and Programming
float
double
OO Design
CS445 - Object Oriented Design and Programming
Topics
Class Basics and Benefits
Creating Objects Using Constructors
Calling Methods
Using Object References
CS445 - Object Oriented Design and Programming
Object-Oriented Programming
Classes combine data and the methods (code)
to manipulate the data
Classes are a template used to create specific
objects
All Java programs consist of at least one class.
Two types of classes
– Application/Applet classes
– Service classes
CS445 - Object Oriented Design and Programming
Example
Student class
– Data: name, year, and grade point average
– Methods: store/get the value of each piece of data,
promote to next year, etc.
Student Object: student1
– Data: Maria Gonzales, Sophomore, 3.5
CS445 - Object Oriented Design and Programming
Some Terminology
Object reference: identifier of the object
Instantiating an object: creating an object of a
class
Instance of the class: the object
Methods: the code to manipulate the object data
Calling a method: invoking a service for an
object.
CS445 - Object Oriented Design and Programming
Class Data
Instance variables: variables defined in the
class and given values in the object
Fields: instance variables and static variables
(we'll define static later)
Members of a class: the class's fields and
methods
Fields can be:
– any primitive data type (int, double, etc.)
– objects
CS445 - Object Oriented Design and Programming
Encapsulation
Implementation of a module should be separated from
its users.
Instance variables are usually declared to be private,
which means users of the class must reference the
data of an object by calling methods of the class.
Thus the methods provide a protective shell around the
data. We call this encapsulation.
Benefit: the class methods can ensure that the object
data is always valid.
CS445 - Object Oriented Design and Programming
Modularity
Divide-and-conquer
Decompose a complex system into a highly
cohesive loosely coupled modules.
– Cohesion single-mind-ness of a module
• Each module should small and simple
– Coupling the degree of connectivity between modules
• Interactions between modules should be simple
CS445 - Object Oriented Design and Programming
Abstraction
Separating the essential from the nonessential
The behaviors of a module should be
characterized in a precise way using its
interfaces.
Server provider for example is a client that
provide services (methods) to it’s clients.
– Clients need to know only the contract API.
CS445 - Object Oriented Design and Programming
Polymorphism
Many shapes
Same method many ways to call it (dynamic)
Replacing an object with its parent
CS445 - Object Oriented Design and Programming
Reusability
Reuse: class code is already written and tested,
so you build a new application faster and it is
more reliable
Example: A Date class could be used in a
calendar program, appointment-scheduling
program, online shopping program, etc.
CS445 - Object Oriented Design and Programming
How To Reuse A Class
You don't need to know how the class is written.
You do need to know the application
programming interface (API) of the class.
The API is published and tells you:
– How to create objects
– What methods are available
– How to call the methods
CS445 - Object Oriented Design and Programming
Declare an Object Reference
Syntax:
ClassName objectReference;
or
ClassName objectRef1, objectRef2…;
Object reference holds address of object
Example:
Date d1;
CS445 - Object Oriented Design and Programming
Instantiate an Object
Objects MUST be instantiated before they can
be used
Call a constructor using new keyword
Constructor has same name as class.
Syntax:
objectReference =
new ClassName( arg list );
Arg list (argument list) is comma-separated list
of initial values to assign to object data
CS445 - Object Oriented Design and Programming
Constructor
Constructor method special method with the
same name as the class that is used with new
when a class is instantiated
public class name {
public name(String frst,String lst)
{
first = frst;
last = lst;
}
}
Name name;
name = new Name(“john”, “Dewey”);
CS445 - Object Oriented Design and Programming
Date Class API
constructor: special method that creates an object and
assigns initial values to data
Date Class Constructor Summary
Date( )
creates a Date object with initial month, day,
and year values of 1, 1, 2000
Date( int mm, int dd, int yy )
creates a Date object with initial month, day,
and year values of mm, dd, and yy
CS445 - Object Oriented Design and Programming
Instantiation Examples
Date independenceDay;
independenceDay = new Date( 7, 4, 1776 );
Date graduationDate =
new Date( 5, 15, 2008 );
Date defaultDate = new Date( );
Example Next Slide
CS445 - Object Oriented Design and Programming
Constructors.java
public class Constructors
{
public static void main( String [] args )
{
Date independenceDay;
independenceDay = new Date( 7, 4, 1776 );
Date graduationDate = new Date( 5, 15,
2008 );
Date defaultDate = new Date( );
}
}
Figure Next Slide
CS445 - Object Oriented Design and Programming
Objects After Instantiation
CS445 - Object Oriented Design and Programming
Calling a Method
CS445 - Object Oriented Design and Programming
Method Classifications
Accessor methods
– get…
– gives values of object data
Mutator methods
– set…
– change values of object data
CS445 - Object Oriented Design and Programming
Date Class Methods
Return value
Method name and argument list
int
getMonth( )
int
returns the value of month
getDay( )
int
returns the value of day
getYear( )
void
returns the value of year
setMonth( int mm )
void
sets the value of month to mm
setDay( int dd )
void
sets the value of day to dd
setYear( int yy )
sets the value of year to yy
CS445 - Object Oriented Design and Programming
The Argument List in an API
Pairs of
dataType variableName
Specify
– Order of arguments
– Data type of each argument
Arguments can be:
– Any expression that evaluates to the specified data
type
CS445 - Object Oriented Design and Programming
Modeling Relationships and
Structures
UML
CS445 - Object Oriented Design and Programming
UML Class Diagram
Used to model the static structure and
relationships among the classes of an OO
software system
A class diagram is made of:
– Nodes (Classes and Interfaces)
– Links (Relationships)
CS445 - Object Oriented Design and Programming
Relationships
Inheritance
–
–
–
–
–
Extension Relationship (specialization and generalization)
Extension between two interfaces
Implementation (when a class implements an interface)
UML uses hollow triangle pointing toward the super class
See Page 30 for an example
Association
Aggregation and Composition
Dependency
CS445 - Object Oriented Design and Programming
Read Ahead
Chapter 2 including the case study on
page 44
CS445 - Object Oriented Design and Programming