Programming Paradigms
Download
Report
Transcript Programming Paradigms
IT 240
Programming Paradigms
MS Information Technology
Offshore Program
Ateneo de Davao
Session 3
Course Outline Revisited
Programming Language Concepts
Survey of Languages and Paradigms
Imperative, Functional, Object-Oriented
Focus: OO Programming
OO Languages (Java and C++)
OO Design (UML)
Advanced Topics (Design Patterns)
Schedule This Weekend
Friday Evenin
OOP Concepts
Saturday Morning
OOP Languages: More Java
Saturday Afternoon
OOP Languages: C++, contrast with Java
Intro to OO Design & the Unified Modeling
Language (UML)
Key OOP Concepts
Object, Class
Instantiation, Constructors
Encapsulation
Inheritance and Subclasses
Abstraction
Reuse
Polymorphism, Dynamic Binding
Object
Definition: a thing that has identity, state,
and behavior
identity: a distinguished instance of a class
state: collection of values for its variables
behavior: capability to execute methods
* variables and methods are defined in a class
Class
Definition: a collection of data (fields/
variales) and methods that operate on
that data
data/methods define the
contents/capabilities of the instances
(objects) of the class
a class can be viewed as a factory for
objects
a class defines a recipe for its objects
Instantiation
Object creation
Memory is allocated for the object’s fields
as defined in the class
Initialization is specified through a
constructor
a special method invoked when objects are
created
Encapsulation
A key OO concept: “Information Hiding”
Key points
The user of an object should have access
only to those methods (or data) that are
essential
Unnecessary implementation details should
be hidden from the user
In Java/C++, use classes and access
modifiers (public, private, protected)
Inheritance
Inheritance:
programming language feature that allows
for the implicit definition of variables/methods
for a class through an existing class
Subclass relationship
B is a subclass of A
B inherits all definitions (variables/methods)
in A
Abstraction
OOP is about abstraction
Encapsulation and Inheritance are
examples of abstraction
What does the verb “abstract” mean?
Reuse
Inheritance encourages software reuse
Existing code need not be rewritten
Successful reuse occurs only through
careful planning and design
when defining classes, anticipate future
modifications and extensions
Polymorphism
“Many forms”
allow several definitions under a single
method name
Example:
“move” means something for a person
object but means something else for a car
object
Dynamic Binding
The capability of an implementation to
distinguish between the different forms
during run-time
Visual and Event-driven
Programming
Fits very well with the OO Paradigm
Visual Programming and GUIs
windows, icons, buttons, etc. are objects
created from ready-made classes
Event-driven Programming
execution associated with user interaction
with visual objects that causes the invocation
of other objects’ methods
What’s Next?
OO Languages
how are these concepts implemented in
language platforms such as Java and C++
implementation tradeoffs
OO Design
the success of the paradigm lies on how well
classes are designed
need models and techniques (the UML) that
allow for good planning and design
Report Topic
Part of the requirement for this course is a
report to be presented on my next visit
Topic on OO Paradigm
propose a topic by tomorrow
report on a language, an environment, or an
application of OOP (e.g., files or networking)
Requirements
15-20 minute presentation, 2-page report
hands-on demo (unless excusable)
Java
Computing in the 1990s
The Internet and the WWW
from retrieving documents to executing
remote programs
Graphical User Interfaces (GUIs)
visual and event-driven programming
Object-oriented Programming (OOP)
Java Intro Summary
(Last Session)
Simple Java Application
HelloWorld example
Standalone Java program
public static void main( … ) …
Simple Java Applet
HelloAgain example
Executed through browser or appletviewer
Requires .html file
Lab Exercise 1:
TextCopy Applet
Filename: TextCopy.java
Variables:
two TextField variables
one Button variable
Methods:
init(): creates and displays the UI objects
action(): processes UI events
Invoking Methods on
Objects
Syntax for method invocation
object.methodName(arguments)
Example: message.setText(“Hello”);
calls setText method on a TextField object
To find out what methods are available for
a given class
javap package.name.NameOfClass
ex. javap java.awt.TextField
Java Program Structure
Java Class
(optional) import declarations
class declaration
Class
class name should match its file name
extends for inheritance
contains method/function definitions
The Paradigm Change
From a structured collection of functions
procedural programming
To a collection of interacting objects
object-oriented programming
Procedural Programming
and the Structure Chart
main()
scanf()
compute()
print_results()
printf()
Procedural Programming
and DFDs
Inventory Management
Delivery info
Accept and Post
Delivery
Transaction
Item Master
OO Counterpart:
Object Interaction
new (delivery info)
Encoder
:Transaction
post (item count)
:Item Master
OOP and Object Interaction
Objects pass messages to each other
An object responds to a message by
executing an associated method defined
in its class
Causes a “chain reaction”
The user could be viewed as an object
Depicted in an Object Interaction Diagram
Hello.java Application
println()
System.out
object
HelloAgain Applet:
Creation
USER
1: Open HA.html
BROWSER
2: new
3: paint()
g: Graphics
object
4: drawString()
HelloAgain
Applet
Note: new means the object of class HelloAgain is created
HelloAgain Applet:
Another Scenario
USER
BROWSER
1: Move the
browser window
2: paint()
g: Graphics
object
3: drawString()
HelloAgain
Applet
TextCopy Applet:
Creation
USER
BROWSER
1: Open the .html file
2: new
3: init()
message:
TextField object
4: new
5: setText()
copy:
Button object
TextCopy
Applet
7: new
6: new
destination:
TextField object
TextCopy Applet:
Clicking on the Button
USER
1: Click on button
BROWSER
2: action()
message:
TextField object
3: getText()
copy:
Button object
HelloAgain
Applet
4: setText()
destination:
Button object
Java Versus C
Language Differences
Compilation and Execution
Data Types and Operators
Variables
Others
C Program
Compilation and Execution
prog.c is compiled to prog.exe
for multiple modules, produce prog.obj first
and then link with other .obj files
prog.exe is a readily executable binarycoded program
Execution begins with the function
“main()” in the C program
Java Program
Compilation and Execution
Prog.java is compiled to Prog.class
Execution
for applets, the browser loads Prog.class
and UI events can then be processed
for applications, a Java interpreter loads
Prog.class and causes program execution to
begin in the “main()” method of this class
The Java Virtual Machine
Browsers and the Java interpreters have
to simulate this “standard” machine
“Compile once, run anywhere”
Class Loader
The JVM facilitates the loading and
execution of classes
Several classes, not just one class, are
loaded
Java class library
Data Types
Most C types apply to Java
int, char, float, double
Other “primitive” types
short, long (also available in C)
byte, boolean
Main difference
In Java, the size of a data type type is
strictly specified (in C, size depends on the
machine)
Value Ranges for the
Java Data Types
boolean: true, false
size: 1 bit
Not compatible with integer types as in C
char: Unicode character set
size: 2 bytes
Superset of ASCII
Internationalization
Still compatible with integer types
Sizes and Ranges
for Other Java Types
int: 4 bytes
-2,147,483,648 to 2,147,483,647
float: 4 bytes
1.01e-45 to 3.40e+38
double 8 bytes
4.94e-324 to 1.80e+308
Operators
All operators in C apply
&&, ||, and, ! now apply to boolean
operands only
& and | as boolean operators do not
perform “short-cutting”
can be distinguished from integral bitwise
operations
+ for String concatenation
Two Kinds of Variables
Variables of a primitive type
e.g., int x; char c;
Variables of a reference type (class)
e.g., Button b; String s;
Conventions
Primitive types are reserved words in Java
and are indicated in all-lower-case letters
Class names: first letter usually capitalized
Variables and Values
Primitive type variables
int x;
…
x = 5;
X
X
5
Variables and References
Reference type variables
X
Button x;
…
x = new Button(“copy”);
Button Object
X
“copy”
The new Keyword
new Button(“copy”) creates a Button
object and returns a reference (an
address) to that object that a Button
variable could hold
Button Object
X
1023
1023:
1023 is some address in memory
“copy”
The null Keyword
Use null to indicate (or test) that the
variable does not currently refer to an
object
x = null;
if (x == null) ...
X
null
Global Variables
Java has no global variables
Scope of variables analogous to a single C
source program containing several
functions
Within a class, variables declared outside the
methods are available to every method*
Variables declared within a method
(including parameters) are local to that
method
Prototypes in C
In C, prototypes are sometimes required
double squareroot(int); /* prototype */
…
d = squareroot(5); /* used before definition */
…
double squareroot(int num) … /* definition */
In Java, the compiler reads the program
at least twice to resolve usage
#include vs import
In C,
#include <somefile.h> contains the macros
and prototypes that enable a program to call
functions defined in the standard library
In Java,
import some.package.*; enables a program
to refer to existing classes (particularly those
from the class library) by its simple name
(Button versus java.awt.Button)
Statements
All control structures follow the same
syntax (if, switch, while, do-while, for)
In a compound statement or block,
variable declarations and statements may
intersperse
New statement for exception handling:
try-catch
Arrays
Declaration: double nums[];
Creation:
nums = new double[8];
Use:
nums[3] = 6.6;
* Note: starting index is 0 (0 to 7, above)
Visualizing an Array
nums
nums = new double[8];
6.6
double nums[];
nums[3] = 6.6;
Array of Objects
slots
TextField object
TextField object
TextField object
TextField object
TextField object
Classes and Objects
in Java
Variables and Objects
Let Circle be a class with:
variable r that indicates its radius
method area() that computes its area
Declaration:
Circle c;
Instantiation:
c = new Circle();
Usage:
c.r = 5.5;
System.out.println(c.area());
The complete Circle class
public class Circle {
public double x,y; // center coordinates
public double r; // radius
// the methods
public double circumference()
{ return 2*3.14*r; }
public double area() { return 3.14*r*r; }
}
Using the Circle class
public class TestCircle {
public static void main(String args[]) {
Circle c;
c = new Circle();
c.x = 2.0; c.y = 2.0; c.r = 5.5;
System.out.println(c.area());
}
}
The this keyword
this refers to the current object
In the Circle class, the following
definitions for area() are equivalent:
public double area() { return 3.14 * r * r; }
public double area() { return 3.14 * this.r * this.r; }
Using the keyword clarifies that you are
referring to a variable inside an object
dot operator used consistently
Constructors
A constructor is a special type of
method
has the same name as the class
It is called when an object is created
new Circle(); // “calls” the Circle() method
If no constructor is defined, a default
constructor that does nothing is
implemented
A constructor for the
Circle class
public class Circle {
public double x,y; // center coordinates
public double r; // radius
public Circle() {
// sets default values for x, y, and r
this.x = 0.0; this.y = 0.0; this.r = 1.0;
}
...
}
A constructor with
parameters
public class Circle {
…
public Circle(double x, double y, double z) {
this.x = x; this.y = y; this.r = z;
// using this is now a necessity
}
...
}
Using the different
constructors
Circle c, d;
c = new Circle();
// radius of circle has been set to 1.0
System.out.println(c.area());
d = new Circle(1.0,1.0,5.0);
// radius of circle has been set to 5.0
System.out.println(d.area());
Method Overloading
In Java, it is possible to have several
method definitions under the same name
but the signatures should be different
Signature:
the name of the method
the number of parameters
the types of the parameters
Encapsulation in Java
Access modifiers
public
a public variable/method is available for use
outside the class it is defined in
private
a private variable/method may be used only
within the class it is defined in
The Circle class Revisited
public class Circle {
private double x,y; // center coordinates
private double r; // radius
// ...
}
// when using the Circle class ...
Circle c;
c.r = 1.0; // this statement is not allowed
Outside access
to private data
No direct access
Define (public) set and get methods
instead or initialize the data through
constructors
Why?
If you change your mind about the names
and even the types of these private data, the
code using the class need not be changed
Set and Get Methods
Variables/attributes in a class are often
not declared public
Instead:
define use a (public) set method to assign a
value to a variable
define a get method to retrieve that value
Consistent with encapsulation
Set and Get Methods for
Radius
public class Circle {
// ...
private double r; // radius
// …
public void setRadius(double r) { this.r = r; }
public double getRadius() { return this.r; }
// ...
}
Inheritance in Java
The extends Keyword
In Java,
public class B extends A { … }
means B is a subclass of A
objects of class B now have access* to
variables and methods defined in A
The EnhancedCircle class
public class EnhancedCircle extends Circle {
// as if area(), circumference(), setRadius() and getRadius()
// automatically defined; x,y,r are also present (but are private
// to the the Circle class)
private int color;
public void setColor(int c) { this.color = c; }
public void draw() { … }
public double diameter() {
return this.getRadius()*2; }
}
Using a Subclass
EnhancedCircle c;
c = new EnhancedCircle();
// Circle() constructor
// implicitly invoked
c.setColor(5);
c.setRadius(6.6);
System.out.println(c.area());
System.out.println(c.diameter());
c.draw();
Applets and Inheritance
Java Applets that we write extend the
Applet class (defined in package
java.applet)
Methods such as add() (for adding visual
components) are actually methods
available in the Applet class
init(), action(), and paint() are also
available but can be overridden
Class Hierarchy
Subclass relationship forms a hierarchy
Example: TextField class
TextField extends TextComponent which
extends Component which extends Object
Object is the topmost class in Java
Exercise (use javap):
determine where the methods setText() and
getText() are defined
Superclass Variables,
Subclass Objects
Let B be a subclass of A
It is legal to have variables of class A to
refer to objects of class B
Example
Circle c;
…
c = new EnhancedCircle();
Method Overriding
A method (with a given signature) may be
overridden in a subclass
Suppose class B extends A
let void operate() be a method defined in A
void operate() may be defined in B
objects of class A use A’s operate()
objects of class B use B’s operate()
Dynamic Binding
Let A be a superclass of subclasses B and
C
A variable of class A may refer to
instances of A, B, and C
Java facilitates the calling of the
appropriate method at run time
Example
A v; … v.operate();
Constructors and
Superclasses
Suppose B extends A
new B() calls B’s constructor
how about A’s constructor ?
Rule
the constructor of a superclass is always
invoked before the statements in the
subclass’ constructor are executed
super()
Used to call a superclass’ constructor
Implicitly included when not indicated
If B extends A, the following are equivalent:
public B() {
// body of constructor
}
public B() {
super();
// body of constructor
}
Calling a particular
Constructor
Use super with parameters if a particular
constructor should be called
Example:
public class BlueButton extends Button {
public BlueButton(String s) {
super(s); // without this, super() is called (label-less)
setBackground(Color.blue);
}…
}
More Uses for super
When overriding a method, one can
merely “extend” the method definition
public class Manager extends Employee {
public void increase() {
super.increase(); // call Employee’s increase
// do more stuff
}
}
Visual and Event-Driven
Programming in Java
Lab Exercise II
Create a BankAccount class
Methods: deposit(), withdraw(), getBalance(),
addInterest()
Create a separate Bank class (Java application)
that tests BankAccount
Create BankAccount object(s) and invoke methods
Create a CheckingAccount class
Methods: same as BankAccount, but add a
drawCheck method
Add code in Bank to test CheckingAccount
The Java AWT
Components
Button, TextField, Label, Panel
Others
Layout Managers
FlowLayout, GridLayout, BorderLayout
CardLayout, GridBagLayout
* add() in applet
Components
Button: clickable visual object
Label: text
TextField
contains editable text
setText() and getText()
Panel
contains other visual components
setLayout() and add()
Layout Managers
FlowLayout
objects are placed row by row, left to right
GridLayout
divides container into an m by n grid
BorderLayout
divides container into 5 parts
Center, North, South, East, West
Event Processing in the
(old) JDK 1.0.2
What needs to be done
init() method: create visual components and
add them to the applet
action(): determine which button was clicked
and indicate associated action
Problems
nested if-statement in action() inefficient
code associated with visual object far from
its definition
Event Processing in
JDK 1.1 and higher
Listener objects
responsible for processing UI events
specifies actions that corresponds to an
event
JDK 1.1
need to associate a listener for every visual
object that the user interacts with
listener should implement method(s) that
specify corresponding actions
Graphics in Java
The paint() method
Takes a Graphics object as a parameter
Graphics methods:
drawString(s, x, y);
drawOval(x, y, r1, r2);
drawRect(x1, y1, x2, y2);
javap java.awt.Graphics
paint()
Describes “current picture” of the applet
repaint()
method of Applet
call this method when your drawing should
be updated
automatically called but system not always
aware of updates
Example: MovingCircle
Extends Applet
Variables
x, y, r: position and size of circle
move: Button variable
Methods:
init(): initialize variables
action(): when button pressed, update x
paint(): g.drawOval(x,y,r,r);
Lab Exercise III
Implement MovingCircle
Arrange it so that a Circle class is used
define and initialize a Circle object in the
applet
instead of x, y, and r
Maintain several Circle objects
have an “add” button that adds Circles
Java vs C++
Outline
Program Structure and Execution
Encapsulation and Inheritance
Objects and Variables
Constructors
Methods and Operators
Containers and Reuse
GUI Programming
Program Structure
Class definition similar in Java and C++
Java: two types of programs
application (with main() function)
applet (typically embedded in a web page)
C++
a program is still a collection of functions
that may use objects and classes
main() function serves as driver
Program Execution
Java: Virtual Machine (VM)
programs: both compiled and interpreted
compiler produces .class from .java
VM loads .class file(s) as needed
C++: compiled, linked, and loaded
modules separately compiled
linked to produce executable
static vs dynamic libraries
Encapsulation
Enforced through access keywords
public: for interface
private: to make implementation inaccessible
protected: access for subclasses only
In Java
each member is prefixed with a keyword
In C++
public, private, and protected sections
Breaking Encapsulation
Possible in C++ through the friend
keyword
A method or class may be declared as a
friend of an existing class
Allows access to private members
“A friend is someone who has access to
your private parts.”
Inheritance
Feature that allows a class to be defined
based on another class
methods and attributes are inherited
Java and C++ difference
Java: public class A extends B { … }
C++: class A: B { … }
Multiple inheritance possible in C++, not
in Java
Objects and Identity
Questions:
How/when are objects created?
What is the relationship between a variable
and an object?
Difference between Java and C++
distinction between primitive (built-in) type
variables and variables for objects
reference relationship between variable and
actual object
Variables for Built-in Types
Variables for built-in types (C++ and
Java)
X
int x;
…
x = 5;
X
5
Reference Variables
(in Java)
Reference type variables
X
Button x;
…
x = new Button(“click”);
Button Object
X
“click”
Variables That “hold”
Objects (in C++)
Declaration of an object variable allocates
space for the object
Button x(“Click”);
X
“click”
Pointers (in C++)
Variables can be explicitly declared as
pointers to objects
X
Button *x;
…
x = new Button(“click”);
Button Object
X
“click”
Object Construction
Constructor
place where you include code that initializes
the object
Default Constructor
no additional info required
User-defined Constructor
with parameters that specify values or sizes
Constructors in Java and
C++
In Java,
a constructor is invoked only through the
new keyword
recall that all object variables are references
In C++,
a constructor is called upon variable
declaration, or explicitly through new with
pointers, or in other situations
other types of constructors
C++ Control Over Copy and
Assignment
In C++, the semantics of “a = b“
(assignment) can be specified
by defining the copy-assignment operator
In C++, there is a copy constructor
specifies what happens during object
copying, e.g., when function parameters are
passed
There is more low-level control
shallow copy vs deep copy
Methods
Defines object behavior
Static methods vs instance methods
Method overloading
within class, two methods with the same
name but different signatures
Method overriding
same signatures across different classes
(subclass and superclass)
Operators
In C++, operators like =, +, *, ==, etc.
can be defined, just like methods
Example:
class Matrix {
// ...
Matrix operator+(Matrix m) { … } // …
}
c = a + b; // equiv to c = a.operator+(b);
Containers
Examples: Lists, Stacks, Files, etc.
Structures that “contain” elements
Often, the element’s type has little or
nothing to do with the containers’
operations
Possible room for re-use
unified container code for a stack of
integers, a stack of webpages, a stack of
strings, ...
Java and the Object
Hierarchy
All classes extend the Object class:
A variable of class Object can refer to any
Java object
Example:
public class Stack {
Object A[]; int top; // …
void push(Object elt) // ...
}
C++ and Templates
Templates allow for a generic definition
parameterized definition, where the element
type is the parameter
Example:
template<class T>
public class Stack<T> {
T A[MAX]; int top;
void push(T element) // …
}
GUI Programming
In Java, GUI is part of its development kit
java.awt.* is a collection of classes that
support visual programming and graphics
visual objects (buttons, textfields, etc),
layout managers, events, etc.
In C++
not part of the language
libraries dependent on platform (MFCs and
Motif)
Object-Oriented
Design and the UML
Object-Oriented Modeling
UML: Unified Modeling Language
Emerging OO Modeling Standard
What is depicted?
System functionality
Class details and static relationships
Object interaction
State transition within an object
Modeling Techniques
Use Cases/Use Case Diagrams
Class Diagrams
CRC Cards
Interaction Diagrams
State Diagrams
Example:
Use Case Diagram
LIBRARY SYSTEM
Facilitate Borrow
Librarian
Search for Book
Facilitate Return
Borrower
Class Diagrams
and CRC Cards
Class Diagrams: similar to ER Diagrams
but in addition, it incorporates
methods, not just attributes for each entity
inheritance
Class-Responsibility-Collaboration Cards
technique that depicts responsibilities of
classes with respect to other classes (hints on
both data and behavior details)
Example:
Interaction Diagram
Borrow
Screen
2: checkIfAvailable()
:Book
1: checkIfDelinquent()
3: borrowBook()
4: setBorrower()
:Borrower
Example:
State Diagram (Book)
start
Reserved
Borrowed
New
Librarian activates
book as available
Borrower returns book
Available
Object-Oriented Design
Models
Static Model
Class Diagrams
Dynamic Model
Use Cases, Interaction Diagrams, State
Diagrams, others
OO Static Model
Class Diagrams
Relationships
Association
Aggregation/Composition
Inheritance
Attribute and Method names
Classes in a Class Diagram
Class name only
Example
Class Name
Bank
Account
With Details
Class Name
attributes
methods
Example
Bank Acct
double balance
deposit()
withdraw()
Relationships
Inheritance (arrow)
example: between Secretary and Employee
Composition/Aggregation (diamond)
example: between Car and Wheel
Association (line)
example: between Borrower and Book
Inheritance
Employee
public class Secretary extends Employee {
…
}
Secretary
Composition
Car
4
w[]
public class Car {
Wheel w[];
...
public Wheel() {
w = new Wheel[4];
…
}
...
}
Wheel
Association
1
3
Borrower
Book
currBorr
public class Borrower {
Book bk[];
…
public Borrower() {
bk = new Book[3];
}
}
bk[]
public class Book {
Borrower currBorr;
…
}
OO Dynamic Model
Goal: Represent
Object behavior
Object interaction
Traditional (relational) Dynamic Modeling
Data Flow Diagrams (DFDs)
Problem: Processes separate from data
Need modeling notation that highlight tight
relationship between data & processes
DFD Example
(Inventory Management)
Delivery info
Accept and Post
Delivery
Transaction
Item Master
OO Counterpart:
Object Interaction
new (delivery info)
Encoder
:Transaction
post (item count)
:Item Master
Building an
OO Dynamic Model
Identify use cases
Describe each use cases through an
Interaction Diagram
Derive implied methods (and attributes)
Use Cases
What is a Use Case (Scenario) ?
Typical interaction between user and the
system
Set of use cases <-> system’s functions
Examples
word processor: “increase font size of text
portion”
ATM: “withdraw cash from savings account”
Depicting Use Cases
Set of Use Cases for a system
Use Case Diagram
Describing a single Use Case
Text (narrative)
Describing object interaction for a single
Use Case
Interaction Diagram
Example:
Use Case Diagram
LIBRARY SYSTEM
Facilitate Borrow
Librarian
Search for Book
Facilitate Return
Borrower
Example: Use Case
Facilitate Borrow:
Given a borrower’s ID Card and the book to
be borrowed, the librarian enters the
borrower’s ID number and the book’s
catalogue number. If the borrower is allowed
to borrow the book, the system displays that
the book has been recorded as borrowed
Objects/Classes involved:
Book, Borrower, Librarian’s Borrow Screen
Use Case Diagram
Notation
Stick Figures - Actors
Ellipses - Use Cases
Links - association between actors and
use cases
<<uses>> and <<extends>>
between use cases
Interaction Diagram
Example
Borrow
Screen
2: checkIfAvailable()
:Book
1: checkIfDelinquent()
3: borrowBook()
4: setBorrower()
:Borrower
Interaction Diagrams
Rectangles: Classes/Objects
Arrows: Messages/Method Calls
Labels on Arrows
sequence number
method name
more details, when necessary (conditions,
parameters, types, return types)
Methods
Interaction Diagrams suggest methods for
classes
consequence on detailed class diagram
The label(s) of an arrow should be a
method of the class the arrow points to
Library System
Borrower class should have at least two
methods (checkIfDelinquent and borrowBook)