+ All Categories
Home > Documents > IT 240 Programming Paradigms MS Information Technology Offshore Program Ateneo de Davao Session 3.

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

Date post: 14-Dec-2015
Category:
Upload: augustine-joseph
View: 214 times
Download: 1 times
Share this document with a friend
Popular Tags:
139
IT 240 Programming Paradigms MS Information Technology Offshore Program Ateneo de Davao Session 3
Transcript
Page 1: IT 240 Programming Paradigms MS Information Technology Offshore Program Ateneo de Davao Session 3.

IT 240Programming Paradigms

MS Information Technology Offshore Program

Ateneo de DavaoSession 3

Page 2: IT 240 Programming Paradigms MS Information Technology Offshore Program Ateneo de Davao Session 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)

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

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)

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

Key OOP Concepts

Object, ClassInstantiation, ConstructorsEncapsulationInheritance and SubclassesAbstractionReusePolymorphism, Dynamic Binding

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

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

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

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

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

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

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

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)

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

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

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

Abstraction

OOP is about abstractionEncapsulation and Inheritance are

examples of abstractionWhat does the verb “abstract” mean?

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

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

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

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

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

Dynamic Binding

The capability of an implementation to distinguish between the different forms during run-time

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

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

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

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

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

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)

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

Java

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

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)

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

Java Intro Summary(Last Session)

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

Simple Java AppletHelloAgain exampleExecuted through browser or

appletviewerRequires .html file

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

Lab Exercise 1:TextCopy Applet

Filename: TextCopy.javaVariables:

two TextField variablesone Button variable

Methods:init(): creates and displays the UI

objectsaction(): processes UI events

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

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

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

Java Program Structure

Java Class(optional) import declarationsclass declaration

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

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

The Paradigm Change

From a structured collection of functionsprocedural programming

To a collection of interacting objectsobject-oriented programming

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

Procedural Programming and the Structure Chart

main()

compute()scanf() print_results()

printf()

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

Procedural Programming and DFDs

Accept and PostDelivery

Item Master

Transaction

Delivery info

Inventory Management

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

OO Counterpart:Object Interaction

Encoder

:Item Master

:Transaction

new (delivery info)

post (item count)

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

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

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

Hello.java Application

System.outobject

println()

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

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

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

HelloAgain Applet:Another Scenario

USER BROWSER

HelloAgainApplet

g: Graphicsobject

1: Move the browser window

2: paint()

3: drawString()

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

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

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

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()

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

Java Versus C

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

Language Differences

Compilation and ExecutionData Types and OperatorsVariablesOthers

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

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

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

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

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

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

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

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)

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

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

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

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

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

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

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

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

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

Variables and Values

Primitive type variables

int x; …x = 5;

5

X

X

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

Variables and References

Reference type variables

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

X

X

“copy”

Button Object

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

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

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

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

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

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

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

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

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

#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)

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

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

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

Arrays

Declaration: double nums[];Creation: nums = new double[8];Use: nums[3] = 6.6;

* Note: starting index is 0 (0 to 7, above)

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

Visualizing an Array

6.6

nums

double nums[];

nums = new double[8];

nums[3] = 6.6;

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

Array of Objects

TextField objectslots

TextField object

TextField object

TextField objectTextField object

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

Classes and Objectsin Java

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

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());

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

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; }}

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

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()); }}

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

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

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

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

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

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; } ...}

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

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 } ...}

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

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());

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

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

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

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

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

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

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

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

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

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

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

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; } // ...}

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

Inheritance in Java

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

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

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

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; }

}

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

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();

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

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

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

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

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

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();

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

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()

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

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();

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

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

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

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

}

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

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);

} …

}

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

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 }}

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

Visual and Event-Driven Programming in Java

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

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

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

The Java AWT

ComponentsButton, TextField, Label, PanelOthers

Layout ManagersFlowLayout, GridLayout, BorderLayoutCardLayout, GridBagLayout

* add() in applet

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

Components

Button: clickable visual object Label: textTextField

contains editable textsetText() and getText()

Panelcontains other visual componentssetLayout() and add()

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

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

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

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

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

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

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

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

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

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

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

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);

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

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

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

Java vs C++

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

Outline

Program Structure and Execution Encapsulation and InheritanceObjects and VariablesConstructorsMethods and OperatorsContainers and ReuseGUI Programming

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

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

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

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

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

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

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

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.”

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

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

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

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

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

Variables for Built-in Types

Variables for built-in types (C++ and Java)

int x; …x = 5; 5

X

X

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

Reference Variables(in Java)

Reference type variables

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

X

X

“click”

Button Object

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

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

Declaration of an object variable allocates space for the object

Button x(“Click”);

“click”

X

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

Pointers (in C++)

Variables can be explicitly declared as pointers to objects

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

X

X

“click”

Button Object

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

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

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

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

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

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

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

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)

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

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);

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

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, ...

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

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) // ...}

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

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) // …}

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

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)

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

Object-OrientedDesign and the UML

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

Object-Oriented Modeling

UML: Unified Modeling LanguageEmerging OO Modeling Standard

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

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

Modeling Techniques

Use Cases/Use Case DiagramsClass DiagramsCRC CardsInteraction DiagramsState Diagrams

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

Example:Use Case Diagram

Facilitate Borrow

Facilitate Return

Search for Book

LIBRARY SYSTEM

BorrowerLibrarian

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

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)

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

Example:Interaction Diagram

BorrowScreen

:Borrower

:Book

1: checkIfDelinquent()3: borrowBook()

2: checkIfAvailable()

4: setBorrower()

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

Example:State Diagram (Book)

New

Available

Reserved

Borrowed

start

Librarian activatesbook as available

Borrower returns book

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

Object-Oriented Design Models

Static ModelClass Diagrams

Dynamic ModelUse Cases, Interaction Diagrams, State

Diagrams, others

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

OO Static Model

Class DiagramsRelationships

AssociationAggregation/CompositionInheritance

Attribute and Method names

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

Classes in a Class Diagram

Class name only Example

With Details Example

Class Name

Class Nameattributesmethods

BankAccount

Bank Acctdouble balance

deposit()withdraw()

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

Relationships

Inheritance (arrow)example: between Secretary and

EmployeeComposition/Aggregation (diamond)

example: between Car and WheelAssociation (line)

example: between Borrower and Book

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

Inheritance

Secretary

Employee

public class Secretary extends Employee { …}

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

Composition

Car Wheel4

w[]

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

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

Association

Borrower BookcurrBorr bk[]

31

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

public class Book { Borrower currBorr; …}

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

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

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

DFD Example(Inventory Management)

Accept and PostDelivery

Item Master

Transaction

Delivery info

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

OO Counterpart:Object Interaction

Encoder

:Item Master

:Transaction

new (delivery info)

post (item count)

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

Building anOO Dynamic Model

Identify use casesDescribe each use cases through an

Interaction DiagramDerive implied methods (and

attributes)

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

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”

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

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

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

Example:Use Case Diagram

Facilitate Borrow

Facilitate Return

Search for Book

LIBRARY SYSTEM

BorrowerLibrarian

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

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

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

Use Case Diagram Notation

Stick Figures - ActorsEllipses - Use CasesLinks - association between actors

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

between use cases

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

Interaction Diagram Example

BorrowScreen

:Borrower

:Book

1: checkIfDelinquent()3: borrowBook()

2: checkIfAvailable()

4: setBorrower()

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

Interaction Diagrams

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

sequence numbermethod namemore details, when necessary

(conditions, parameters, types, return types)

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

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)


Recommended