IT 240 Programming Paradigms MS Information Technology Offshore Program Ateneo de Davao Session 3.

Post on 14-Dec-2015

214 Views

Category:

Documents

1 Downloads

Preview:

Click to see full reader

Transcript

IT 240Programming Paradigms

MS Information Technology Offshore Program

Ateneo de DavaoSession 3

Course Outline Revisited

Programming Language ConceptsSurvey of Languages and Paradigms

Imperative, Functional, Object-OrientedFocus: OO Programming

OO Languages (Java and C++)OO Design (UML) Advanced Topics (Design Patterns)

Schedule This Weekend

Friday EveninOOP Concepts

Saturday MorningOOP Languages: More Java

Saturday AfternoonOOP Languages: C++, contrast with

JavaIntro to OO Design & the Unified

Modeling Language (UML)

Key OOP Concepts

Object, ClassInstantiation, ConstructorsEncapsulationInheritance and SubclassesAbstractionReusePolymorphism, Dynamic Binding

Object

Definition: a thing that has identity, state, and behavior

identity: a distinguished instance of a classstate: 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 datadata/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 creationMemory is allocated for the object’s

fields as defined in the classInitialization is specified through a

constructora 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 relationshipB is a subclass of AB inherits all definitions

(variables/methods) in A

Abstraction

OOP is about abstractionEncapsulation and Inheritance are

examples of abstractionWhat does the verb “abstract” mean?

Reuse

Inheritance encourages software reuse

Existing code need not be rewrittenSuccessful reuse occurs only through

careful planning and designwhen defining classes, anticipate future

modifications and extensions

Polymorphism

“Many forms”allow several definitions under a single

method nameExample:

“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 ParadigmVisual Programming and GUIs

windows, icons, buttons, etc. are objects created from ready-made classes

Event-driven Programmingexecution associated with user interaction

with visual objects that causes the invocation of other objects’ methods

What’s Next?

OO Languageshow are these concepts implemented in

language platforms such as Java and C++implementation tradeoffs

OO Designthe success of the paradigm lies on how

well classes are designedneed 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 Paradigmpropose a topic by tomorrowreport on a language, an environment, or an

application of OOP (e.g., files or networking)Requirements

15-20 minute presentation, 2-page reporthands-on demo (unless excusable)

Java

Computing in the 1990s

The Internet and the WWWfrom retrieving documents to executing

remote programsGraphical User Interfaces (GUIs)

visual and event-driven programmingObject-oriented Programming (OOP)

Java Intro Summary(Last Session)

Simple Java ApplicationHelloWorld exampleStandalone Java programpublic static void main( … ) …

Simple Java AppletHelloAgain exampleExecuted through browser or

appletviewerRequires .html file

Lab Exercise 1:TextCopy Applet

Filename: TextCopy.javaVariables:

two TextField variablesone Button variable

Methods:init(): creates and displays the UI

objectsaction(): 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 classjavap package.name.NameOfClassex. javap java.awt.TextField

Java Program Structure

Java Class(optional) import declarationsclass declaration

Classclass name should match its file nameextends for inheritancecontains method/function definitions

The Paradigm Change

From a structured collection of functionsprocedural programming

To a collection of interacting objectsobject-oriented programming

Procedural Programming and the Structure Chart

main()

compute()scanf() print_results()

printf()

Procedural Programming and DFDs

Accept and PostDelivery

Item Master

Transaction

Delivery info

Inventory Management

OO Counterpart:Object Interaction

Encoder

:Item Master

:Transaction

new (delivery info)

post (item count)

OOP and Object Interaction

Objects pass messages to each otherAn 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 objectDepicted in an Object Interaction

Diagram

Hello.java Application

System.outobject

println()

HelloAgain Applet: Creation

USER BROWSER

HelloAgainApplet

g: Graphicsobject

1: Open HA.html

2: new3: paint()

4: drawString()

Note: new means the object of class HelloAgain is created

HelloAgain Applet:Another Scenario

USER BROWSER

HelloAgainApplet

g: Graphicsobject

1: Move the browser window

2: paint()

3: drawString()

TextCopy Applet:Creation

USER BROWSER

TextCopyApplet

message:TextField object

1: Open the .html file

2: new3: init()4: new

5: setText()

destination:TextField object

copy:Button object

6: new7: new

TextCopy Applet:Clicking on the Button

USER BROWSER

HelloAgainApplet

message:TextField object

1: Click on button

2: action()

3: getText()

destination:Button object

copy:Button object

4: setText()

Java Versus C

Language Differences

Compilation and ExecutionData Types and OperatorsVariablesOthers

C ProgramCompilation and Execution

prog.c is compiled to prog.exefor multiple modules, produce prog.obj

first and then link with other .obj filesprog.exe is a readily executable

binary-coded program

Execution begins with the function “main()” in the C program

Java ProgramCompilation and Execution

Prog.java is compiled to Prog.class

Executionfor applets, the browser loads Prog.class

and UI events can then be processedfor 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 Javaint, char, float, double

Other “primitive” typesshort, long (also available in C)byte, boolean

Main differenceIn Java, the size of a data type type is

strictly specified (in C, size depends on the machine)

Value Ranges for theJava Data Types

boolean: true, falsesize: 1 bitNot compatible with integer types as in C

char: Unicode character setsize: 2 bytesSuperset of ASCIIInternationalizationStill compatible with integer types

Sizes and Rangesfor Other Java Types

int: 4 bytes-2,147,483,648 to 2,147,483,647

float: 4 bytes1.01e-45 to 3.40e+38

double 8 bytes4.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 typee.g., int x; char c;

Variables of a reference type (class)e.g., Button b; String s;

ConventionsPrimitive types are reserved words in Java

and are indicated in all-lower-case lettersClass names: first letter usually capitalized

Variables and Values

Primitive type variables

int x; …x = 5;

5

X

X

Variables and References

Reference type variables

Button x; …x = new Button(“copy”);

X

X

“copy”

Button Object

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

“copy”

Button Object

1023:

1023 is some address in memory

1023

X

The null Keyword

Use null to indicate (or test) that the variable does not currently refer to an object

x = null;

if (x == null) ...

null

X

Global Variables

Java has no global variablesScope of variables analogous to a single

C source program containing several functionsWithin 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 requireddouble 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

6.6

nums

double nums[];

nums = new double[8];

nums[3] = 6.6;

Array of Objects

TextField objectslots

TextField object

TextField object

TextField objectTextField object

Classes and Objectsin 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 objectIn 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 objectdot operator used consistently

Constructors

A constructor is a special type of methodhas the same name as the class

It is called when an object is creatednew 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.0System.out.println(c.area());d = new Circle(1.0,1.0,5.0);// radius of circle has been set to 5.0System.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 methodthe number of parametersthe types of the parameters

Encapsulation in Java

Access modifierspublic

a public variable/method is available for use outside the class it is defined in

privatea 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 accessto private data

No direct accessDefine (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 variabledefine a get method to retrieve that

valueConsistent 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 Aobjects 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 hierarchyExample: TextField class

TextField extends TextComponent which extends Component which extends Object

Object is the topmost class in JavaExercise (use javap):

determine where the methods setText() and getText() are defined

Superclass Variables,Subclass Objects

Let B be a subclass of AIt is legal to have variables of class A

to refer to objects of class BExample

Circle c;…c = new EnhancedCircle();

Method Overriding

A method (with a given signature) may be overridden in a subclass

Suppose class B extends Alet void operate() be a method defined

in Avoid operate() may be defined in Bobjects 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

ExampleA v; … v.operate();

Constructors and Superclasses

Suppose B extends Anew B() calls B’s constructorhow about A’s constructor ?

Rulethe constructor of a superclass is always

invoked before the statements in the subclass’ constructor are executed

super()

Used to call a superclass’ constructorImplicitly included when not indicated

If B extends A, the following are equivalent:

public B() { public B() {

// body of constructor 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 classMethods: deposit(), withdraw(), getBalance(),

addInterest()Create a separate Bank class (Java

application) that tests BankAccountCreate BankAccount object(s) and invoke

methodsCreate a CheckingAccount class

Methods: same as BankAccount, but add a drawCheck method

Add code in Bank to test CheckingAccount

The Java AWT

ComponentsButton, TextField, Label, PanelOthers

Layout ManagersFlowLayout, GridLayout, BorderLayoutCardLayout, GridBagLayout

* add() in applet

Components

Button: clickable visual object Label: textTextField

contains editable textsetText() and getText()

Panelcontains other visual componentssetLayout() and add()

Layout Managers

FlowLayoutobjects are placed row by row, left to

rightGridLayout

divides container into an m by n gridBorderLayout

divides container into 5 partsCenter, North, South, East, West

Event Processing in the (old) JDK 1.0.2

What needs to be doneinit() method: create visual components

and add them to the appletaction(): determine which button was

clicked and indicate associated actionProblems

nested if-statement in action() inefficientcode associated with visual object far

from its definition

Event Processing inJDK 1.1 and higher

Listener objectsresponsible for processing UI eventsspecifies actions that corresponds to an

eventJDK 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() methodTakes a Graphics object as a

parameterGraphics 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 Appletcall this method when your drawing

should be updatedautomatically called but system not

always aware of updates

Example: MovingCircle

Extends AppletVariables

x, y, r: position and size of circlemove: Button variable

Methods:init(): initialize variablesaction(): when button pressed, update xpaint(): g.drawOval(x,y,r,r);

Lab Exercise III

Implement MovingCircleArrange it so that a Circle class is

useddefine and initialize a Circle object in

the appletinstead of x, y, and r

Maintain several Circle objectshave an “add” button that adds Circles

Java vs C++

Outline

Program Structure and Execution Encapsulation and InheritanceObjects and VariablesConstructorsMethods and OperatorsContainers and ReuseGUI 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 classesmain() function serves as driver

Program Execution

Java: Virtual Machine (VM)programs: both compiled and interpretedcompiler produces .class from .javaVM loads .class file(s) as needed

C++: compiled, linked, and loadedmodules separately compiledlinked to produce executablestatic vs dynamic libraries

Encapsulation

Enforced through access keywordspublic: for interfaceprivate: to make implementation

inaccessibleprotected: access for subclasses only

In Javaeach 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 classmethods and attributes are inherited

Java and C++ differenceJava: 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)

int x; …x = 5; 5

X

X

Reference Variables(in Java)

Reference type variables

Button x; …x = new Button(“click”);

X

X

“click”

Button Object

Variables That “hold” Objects (in C++)

Declaration of an object variable allocates space for the object

Button x(“Click”);

“click”

X

Pointers (in C++)

Variables can be explicitly declared as pointers to objects

Button *x; …x = new Button(“click”);

X

X

“click”

Button Object

Object Construction

Constructorplace where you include code that

initializes the objectDefault Constructor

no additional info requiredUser-defined Constructor

with parameters that specify values or sizes

Constructors in Java and C++

In Java,a constructor is invoked only through the

new keywordrecall 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 specifiedby defining the copy-assignment operator

In C++, there is a copy constructorspecifies what happens during object

copying, e.g., when function parameters are passed

There is more low-level controlshallow copy vs deep copy

Methods

Defines object behaviorStatic methods vs instance methodsMethod overloading

within class, two methods with the same name but different signatures

Method overridingsame 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” elementsOften, the element’s type has little or

nothing to do with the containers’ operations

Possible room for re-useunified 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 objectExample:

public class Stack { Object A[]; int top; // … void push(Object elt) // ...}

C++ and Templates

Templates allow for a generic definitionparameterized definition, where the

element type is the parameterExample:

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 kitjava.awt.* is a collection of classes that

support visual programming and graphicsvisual objects (buttons, textfields, etc),

layout managers, events, etc.In C++

not part of the languagelibraries dependent on platform (MFCs and

Motif)

Object-OrientedDesign and the UML

Object-Oriented Modeling

UML: Unified Modeling LanguageEmerging OO Modeling Standard

What is depicted?System functionalityClass details and static relationshipsObject interactionState transition within an object

Modeling Techniques

Use Cases/Use Case DiagramsClass DiagramsCRC CardsInteraction DiagramsState Diagrams

Example:Use Case Diagram

Facilitate Borrow

Facilitate Return

Search for Book

LIBRARY SYSTEM

BorrowerLibrarian

Class Diagramsand CRC Cards

Class Diagrams: similar to ER Diagrams but in addition, it incorporatesmethods, not just attributes for each entityinheritance

Class-Responsibility-Collaboration Cardstechnique that depicts responsibilities of

classes with respect to other classes (hints on both data and behavior details)

Example:Interaction Diagram

BorrowScreen

:Borrower

:Book

1: checkIfDelinquent()3: borrowBook()

2: checkIfAvailable()

4: setBorrower()

Example:State Diagram (Book)

New

Available

Reserved

Borrowed

start

Librarian activatesbook as available

Borrower returns book

Object-Oriented Design Models

Static ModelClass Diagrams

Dynamic ModelUse Cases, Interaction Diagrams, State

Diagrams, others

OO Static Model

Class DiagramsRelationships

AssociationAggregation/CompositionInheritance

Attribute and Method names

Classes in a Class Diagram

Class name only Example

With Details Example

Class Name

Class Nameattributesmethods

BankAccount

Bank Acctdouble balance

deposit()withdraw()

Relationships

Inheritance (arrow)example: between Secretary and

EmployeeComposition/Aggregation (diamond)

example: between Car and WheelAssociation (line)

example: between Borrower and Book

Inheritance

Secretary

Employee

public class Secretary extends Employee { …}

Composition

Car Wheel4

w[]

public class Car { Wheel w[]; ... public Wheel() { w = new Wheel[4]; … } ...}

Association

Borrower BookcurrBorr bk[]

31

public class Borrower { Book bk[]; … public Borrower() { bk = new Book[3]; }}

public class Book { Borrower currBorr; …}

OO Dynamic Model

Goal: RepresentObject behaviorObject interaction

Traditional (relational) Dynamic ModelingData Flow Diagrams (DFDs)Problem: Processes separate from dataNeed modeling notation that highlight tight

relationship between data & processes

DFD Example(Inventory Management)

Accept and PostDelivery

Item Master

Transaction

Delivery info

OO Counterpart:Object Interaction

Encoder

:Item Master

:Transaction

new (delivery info)

post (item count)

Building anOO Dynamic Model

Identify use casesDescribe each use cases through an

Interaction DiagramDerive implied methods (and

attributes)

Use Cases

What is a Use Case (Scenario) ?Typical interaction between user and the

systemSet of use cases <-> system’s functions

Examplesword processor: “increase font size of text

portion”ATM: “withdraw cash from savings

account”

Depicting Use Cases

Set of Use Cases for a systemUse Case Diagram

Describing a single Use CaseText (narrative)

Describing object interaction for a single Use CaseInteraction Diagram

Example:Use Case Diagram

Facilitate Borrow

Facilitate Return

Search for Book

LIBRARY SYSTEM

BorrowerLibrarian

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 - ActorsEllipses - Use CasesLinks - association between actors

and use cases<<uses>> and <<extends>>

between use cases

Interaction Diagram Example

BorrowScreen

:Borrower

:Book

1: checkIfDelinquent()3: borrowBook()

2: checkIfAvailable()

4: setBorrower()

Interaction Diagrams

Rectangles: Classes/ObjectsArrows: Messages/Method CallsLabels on Arrows

sequence numbermethod namemore details, when necessary

(conditions, parameters, types, return types)

Methods

Interaction Diagrams suggest methods for classesconsequence on detailed class diagram

The label(s) of an arrow should be a method of the class the arrow points to

Library SystemBorrower class should have at least two

methods (checkIfDelinquent and borrowBook)

top related