DT265-2 Object Oriented Software Development 2 Lecture 2 : Revision Lecturer Pat Browne patrick.browne@dit.ie.

Post on 11-Jan-2016

221 Views

Category:

Documents

0 Downloads

Preview:

Click to see full reader

Transcript

DT265-2 Object Oriented Software Development 2

Lecture 2 : Revision

Lecturer Pat Brownepatrick.browne@dit.ie

A Programming Paradigm

• Object-oriented programming is frequently referred to as a programming paradigm. Other programming paradigms include the imperative-programming paradigm, the logic programming paradigm, and the functional-programming paradigm.

A Way of Viewing the World

• Suppose an individual named Chris wishes to send flowers to a friend named Robin, who lives in another city.

• Chris simply walks to a nearby flower shop and initiates a sequence of events that results in Robin receiving the flowers.

1.4.1 Agents and Communities

Agents and Communities

• The mechanism that was used to describe the flower situation was to find an appropriate agent (florist) and to pass to this agent a message containing a request. It is the responsibility of the florist to satisfy the request. There is some method used by the florist to do this. Chris does not need to know the particular method that the florist will use to satisfy the request; indeed, often the person making a request does not want to know the details. This information is usually hidden from inspection.

Agents and Communities

Agents and Communities

Agents and Communities

• An object oriented system is structured as a community of interacting agents, called objects. Each object has a role to play. Each object provides a service, or performs an action, that is used by other members of the community.

Messages and Methods

• The chain reaction that ultimately resulted in the solution to Chris's requirement for flowers began with a request given to the florist. This request lead to other requests, which lead to still more requests, until the flowers ultimately reached Chris's friend Robin. The members of this community interact with each other by making requests. An objects contains a list of actions it can perform.

Classes and Instances• We can use the term Florist to represent the

category (or class) of all florists. This is an example of a basic principle of object-oriented programming:

• All objects are instances of a class. • The method invoked by an object in response to a

message is determined by the class of the receiver. All objects of a given class use the same method in response to similar messages.

Class Hierarchies Inheritance• Chris has more information about the florist

(Fred) not necessarily because Fred is a florist but because he is a shopkeeper. Chris knows, for example, that a transfer of money will be part of the transaction, and that in return for payment Fred will offer a receipt. These actions are true of grocers, stationers, and other shopkeepers. Since the category Florist is a more specialized form of the category Shopkeeper, any knowledge Chris has of Shopkeepers is also true of Florists and hence of Fred.

Class Hierarchies & Inheritance

Messages and Methods

• Action is initiated in object-oriented programming by the transmission of a message to an agent (an object) responsible for the action. The message encodes the request for an action and is accompanied by any additional information (arguments) needed to carry out the request. The receiver is the object to whom the message is sent. If the receiver accepts the message, it accepts the responsibility to carry out the indicated action. In response to a message, the receiver will perform some method to satisfy the request.

Messages and Methods

• Note the important principle of information hiding in regard to message passing that is, the client sending the request need not know the actual means by which the request will be honoured.

Messages and Methods• There is another principle implicit in message

passing. If there is a task to perform, the first thought of the client is to find somebody else he or she can ask to do the work.

• An important part of object-oriented programming is the development of reusable components, and an important first step in the use of reusable components is a willingness to trust software written by others (e.g. e-voting).

Object Orientation

Traditional V Objects

Objects and messages

A single Object

A single Object

A single Object receiving a message

A set of object and messages

What Is a Class?

• A class is a blueprint or prototype from which objects are created. This section defines a class that models the state and behaviour of a real-world object. It intentionally focuses on the basics, showing how even a simple class can cleanly model state and behaviour.

What Is an Object?

• An object is a software bundle of related state and behaviour. Software objects are often used to model the real-world objects that you find in everyday life. This lesson explains how state and behaviour are represented within an object, introduces the concept of data encapsulation, and explains the benefits of designing your software in this manner.

What Is Inheritance?

• Inheritance provides a powerful and natural mechanism for organizing and structuring your software. This section explains how classes inherit state and behaviour from their super-classes, and explains how to derive one class from another using the simple syntax provided by the Java programming language.

Accountpublic class Account { protected double balance;

// Constructor to initialise balance public Account( double amount ) { balance = amount;}

// Overloaded constructor for empty balance public Account() { balance = 0.0;}

public void deposit( double amount ) { balance += amount; }

public double withdraw( double amount ) { // See if amount can be withdrawn if (balance >= amount) { balance -= amount; return amount; } else // Withdrawal not allowed return 0.0;}

public double getbalance() { return balance;}}

Account Democlass AccountDemo { public static void main(String args[]) { // Create an empty account Account my_account = new Account();

// Deposit money my_account.deposit(250.00);

// Print current balance System.out.println ("Current balance " + my_account.getbalance());

// Withdraw money my_account.withdraw(80.00);

// Print remaining balance System.out.println ("Remaining balance " + my_account.getbalance()); }}

Savings Accountclass BankAccount {private double balance;

public BankAccount( ){ balance = 0; }

public void BankAccount(double init ){ balance = init; }

public void deposit(double amount){ balance = balance + amount; }

public void withdraw(double amount) { balance = balance - amount; }

public double getBalance( ) { return balance; }}

class SavingsAccount extends BankAccount{ private double interestRate; // instance variable public void SavingsAccont(double rate) // constructor { interestRate = rate; } public void addInterest( ) // instance method { double interest = getBalance() * interestRate / 100; deposit(interest);}}

Park1

Classes for Park1

Tree Class & Instance

Run Park

public class RunPark{ //Creates a new Park object. public static void main(String args[]) {

Park myPark = new Park();}}

Parkpublic class Park{ // ------------------- Object variables --------------------- private GrassArea grass; // Grass private PlayArea play; // Swings and slides private FlowerArea flowers; // Flower bed. private Path path; // Path running through park.

// --------------------- Constructor ------------------------ //Creates the park with its plants and entertainments. public Park() { // Create new objects (composition). grass = new GrassArea(); play = new PlayArea(); flowers = new FlowerArea(); path = new Path(); grass.grow(); }}

Flower Area

public class FlowerArea{ // -------------- Class and object variables ----------------- private Path path; // A winding path through the flowers. // --------------------- Constructors ------------------------ /** Initialises the flower bed by creating a single rose. */ public FlowerArea() { path = new Path(); }}

Grass Areapublic class GrassArea{ // ------------------- Object variables --------------------- private Tree oakTree; // A lovely old oak tree. private Path grassyPath; // Path running through park. // --------------------- Constructor ------------------------ // Creates a grassy area complete with path and tree. public GrassArea() { oakTree = new Tree(); grassyPath = new Path(); }

// ------------------------ Methods -------------------------// Grows the grass and any other features of the grass area. public void grow() { oakTree.grow(); oakTree.displayDetails(); }}

Pathpublic class Path{ // ------- Constructor ----------// Creates a new path. public Path() { System.out.println("The builders have just finished laying the path");

}}

public class Tree{ // ------------------- Object variables --------------------- private float height; // Stores heght of tree. private int age; // Age of tree. // Coordinates of location of tree. private int locationX,locationY; // --------------------- Constructor ------------------------ //Creates a new tree and initialises its state. public Tree() { height = 1; age = 2; locationX = 0; locationY = 0; displayDetails(); }• •

Tree.1

Tree.2 // ----------------------- Methods --------------------------- // Grows the tree by 5% and ages it by a year. public void grow() { height = height + (0.05f * height); age = age + 1; } // Displays details of the tree. public void displayDetails() { System.out.println("Tree is " + age + " years old, "); System.out.print(height + "m tall and found at ("); System.out.println(locationX + "," + locationY + ")"); }}

Park2 with sub-classes

Adding super & sub classes

New Plant super classpublic class Plant { // ------------------- Object variables ---------------------- protected float height; // Stores height of plant. protected int age; // Age of plant. protected int locationX,locationY; // Location of plant. // --------------------- Constructor ------------------------- // Initialises the height and age of the plant. public Plant() { age = 0; height = 0; locationX = 0; locationY = 0; } // ----------------------- Methods --------------------------- // Doubles the height of the plant and ages it by a year. public void grow() { height = height*2; age = age + 1; } // Displays details of the plant. public void displayDetails() { System.out.println("Plant is "+age+" years old and " height+"m tall"); }}

New Flower sub-class

• public class Flower extends Plant{

• // ---- Constructor -------• // Creates a new flower. • public Flower() { System.out.println("A little flower is born."); }}

New Tree sub-classpublic class Tree extends Plant{ //Constructor: //Creates new tree and initialises its state.

public Tree() {// The superclass‘s constructor super();// Usually automatically done height = 1; age = 2; displayDetails(); }

New Tree sub-class

//Grows by 5% and ages it by a year. public void grow() { height = height + (0.05f * height);

age = age + 1; }

New Tree sub-class// Mutator Methods: // Sets a new location for the tree. public void setLocation(int newX, int newY){locationX = newX; locationY = newY;} //Accessor Methods: // Reports current x-location of the tree.public int getLocationX(){return locationX;}

public int getLocationY(){return locationY; }}

Mutator Method see Wood Chapter 3

Accessor Method see Wood Chapter 3

Stacks, Queues, PriorityQueues

• A Stack is a first-in, last-out data structure that pops elements in the opposite order than they were pushed. A Stack could use an Array for its internal storage, although the user is not concerned with this.

• A Queue is a first-in, first-out data structure that pops elements in the same order than they were pushed.

• A PriorityQueue is a form of queue that keeps its elements in a sorted state and pops them based on their sorted order rather than in the order that they were pushed.

Stacks & Queues

Stack as an object

Stack Code.1

public class Stack {// private data to hold stack state private int top; private int[] storage;

// constructorStack(int capacity) { storage = new int[capacity]; top = -1; }

Stack Code.2

void push(int value) { top++; storage[top] = value;}

int top() { return storage[top];}

Stack Code.2int pop() { top--; return storage[top+1];}

boolean isEmpty() { return (top == -1);}

} // end of class// The example program contains a main() method

Dijkstra's shortest path algorithm1

• For a given source vertex (node) in a graph, the algorithm finds the path with lowest cost (i.e. the shortest path) between that vertex and every other vertex. It can also be used for finding costs of shortest paths from a single vertex to a single destination vertex by stopping the algorithm once the shortest path to the destination vertex has been determined.

Dijkstra's shortest path algorithm1

• Visited nodes are labelled with their distance from the source. Initially all nodes are labelled with an infinite distance. Like a breadth-first search, Dijkstra’s algorithm uses a queue of discovered unvisited nodes.

• 1. Give the source node distance 0 and add it to the queue. Give the other nodes infinite distance.

• 2. Remove a vertex from the queue and call its distance d. Find the vertices it is connected to. For each connected vertex with infinite distance, replace the distance with d + 1 and add it to the queue.

• 3. If the queue is not empty, go back to Step 2.

V the set of vertices in the graph, xpaths are next step

F set of vertices whose shortest-path lengths remain to be calculated

V – F (permanent labels) set of vertices whose shortest-path lengths have been calculated

Each iteration moves one vertex from F to (V – F)

Invariant : PF : (V – F) b ∊ (V – F)

Permanent Labels Temporary Labels

Dijkstra’s Shortest Path Algorithm

• Dijkstra’s algorithm for finding the shortest from a to v, involves assigning labels to vertices. Let L(v) denote the label of vertex v. At any point, some vertices have temporary labels and the rest have permanent labels, these are shown in red in the following slides. We let T denote the set of vertices having temporary labels.

Dijkstra’s Shortest Path Algorithm

• If L(v) is a permanent label of v the L(v) is the shortest path to v.

• Initially all vertices have temporary labels.• Each iteration of the algorithm changes the

status of one of the labels from temporary to permanent .

• Terminate when z is not an element of T.

Dijkstra’s Shortest Path Algorithm

• Initialize:• L(a):= 0 • all vn (except a) are labelled .• T := set of all temporary verticeswhile z ∊ T [ choose v ∊ T with min L(v) T := T – {v} for each x ∊ T adjacent to v [ L(x) := min{(L(x), L(v) + w(v,x)}]]

Where w(v,x) is distance from v to x.

a z

b c

d e

2

2

2

4

4

1

3

f g

1

3

5

76

Example Graph G(*)

a z

b c

d e

2

2

2

4

4

1

3

f g

1

3

5

76

Initialized Graph G(*)

0

a z

b c

d e

2

2

2

4

4

1

3

f g

1

3

5

76

After First Iteration Graph G(*)

2

1

LabelsL(b) = min{,0+2} L(f) = min{,0+1}

Chose (v= f ) T as minimum L(v)∊

T := set of all temporary vertices

For each x in T adjacent to v: L(x) = min{Lold(x),L(v)+w(v,x)} Where w(v,x) is distance from v to x.

LabelsL(b) = min{,0+2} L(f) = min{,0+1} L(d) = min{,0+1+3} L(g) = min{,0+1+5}

a z

b c

d e

2

2

2

4

4

1

3

f g

1

3

5

76

After Second Iteration Graph G(*)

2

6

4

1

Chose (v= b ) T as minimum L(v)∊

T := set of all temporary vertices

For each x in T adjacent to v: L(x) = min{Lold(x),L(v)+w(v,x)} Where w(v,x) is distance from v to x.

LabelsL(b) = min{,0+2} L(f) = min{,0+1} L(d) = min{,0+1+3} L(g) = min{,0+1+5}L(c) = min{,0+2+2} L(d) = min{4,0+2+2} --dif. pathL(e) = min{,0+2+4}

a z

b c

d e

2

2

2

4

4

1

3

f g

1

3

5

76

After Third Iteration(*)

42

6

64

1

Chose (v= c ) T as minimum L(v) ∊

For each x in T adjacent to v: L(x) = min{Lold(x),L(v)+w(v,x)} Where w(v,x) is distance from v to x. T := set of all temporary vertices

LabelsL(b) = min{,0+2} L(f) = min{,0+1} L(d) = min{,0+1+3} L(g) = min{,0+1+5}L(c) = min{,0+2+2} L(d) = min{4,0+2+2} dif. PathL(e) = min{,0+2+4} L(e) = min{6,0+2+2+3} dif. PathL(z) = min{,0+2+2+1}

a z

b c

d e

2

2

2

4

4

1

3

f g

1

3

5

76

Fourth Iteration(*)

5

42

6

64

1

Chose (v= d ) T as minimum L(v)∊

For each x in T adjacent to v: L(x) = min{Lold(x),L(v)+w(v,x)} Where w(v,x) is distance from v to x. T := set of all temporary vertices

LabelsL(b) = min{,0+2} L(f) = min{,0+1} L(d) = min{,0+1+3} L(g) = min{,0+1+5}L(c) = min{,0+2+2} L(d) = min{4,0+2+2} dif. PathL(e) = min{,0+2+4} L(e) = min{6,0+2+2+3} dif. PathL(z) = min{,0+2+2+1} L(e) = min{6,0+2+2+4} b,f already min

a z

b c

d e

2

2

2

4

4

1

3

f g

1

3

5

76

Fourth Iteration(*)

5

42

6

64

1

Chose (v= z ) T as minimum L(v)∊

For each x in T adjacent to v: L(x) = min{Lold(x),L(v)+w(v,x)} Where w(v,x) is distance from v to x. T := set of all temporary vertices

LabelsL(b) = min{,0+2} L(f) = min{,0+1} L(d) = min{,0+1+3} L(g) = min{,0+1+5}L(c) = min{,0+2+2} L(d) = min{4,0+2+2} dif. PathL(e) = min{,0+2+4} L(e) = min{6,0+2+2+3} dif. PathL(z) = min{,0+2+2+1} L(e) = min{6,0+2+2+4} b,f already min

a z

b c

d e

2

2

2

4

4

1

3

f g

1

3

5

76

Fourth Iteration(*)

5

42

6

64

1

Terminate zT

For each x in T adjacent to v: L(x) = min{Lold(x),L(v)+w(v,x)} Where w(v,x) is distance from v to x. T := set of all temporary vertices

Shortest Paths0=0(0) 1=63168(0) 2=63267(0) 3=177961(1) 4=231057(5) 5=173983(2) 6=101047(1) 7=210597(6)Two alternative paths 0-to-40-2-5-4=63267+110715+57074= 2310560-1-3-4=63168+114793+56521 = 234482

Distance from 0 to 1 is 63168Distance from 0 to 2 is 63267Distance from 1 to 3 is 114793Distance from 3 to 4 is 56521Distance from 2 to 5 is 110715Distance from 5 to 4 is 57074Distance from 1 to 6 is 37879Distance from 2 to 6 is 41437Distance from 6 to 7 is 109549Distance from 3 to 7 is 38739Distance from 7 to 5 is 40222Distance from 7 to 1 is 116652

Display All Paths n to 0shortest path for 7 to 0 start 6 Distance= 109549 end 7 start 1 Distance= 37879 end 6 start 0 Distance= 63168 end 1shortest path for 6 to 0 start 1 Distance= 37879 end 6 start 0 Distance= 63168 end 1shortest path for 5 to 0 start 2 Distance= 110715 end 5 start 0 Distance= 63267 end 2shortest path for 4 to 0 start 5 Distance= 57074 end 4 start 2 Distance= 110715 end 5 start 0 Distance= 63267 end 2shortest path for 3 to 0 start 1 Distance= 114793 end 3 start 0 Distance= 63168 end 1shortest path for 2 to 0 start 0 Distance= 63267 end 2shortest path for 1 to 0 start 0 Distance= 63168 end 1

a z

b c

0

2

2

1

1

2

3

d e

1

Another Example: 1

LabelsL(b) = min{,0+2} L(d) = min{,0+1}

Choose v ∊ T with minimum L(v)=d

a.2

a,1

a z

b c

0

2

2

1

1

2

3

d e

1

Another Example: 2

LabelsL(b) = min{,0+2} L(d) = min{,0+1} L(e)=min{,0+1+1}

Choose v ∊ T with minimum L(v)=d

d.2

a,2

a.1

a z

b c

0

2

2

1

1

2

3

d e

1

Another Example: 3

LabelsL(b) = min{,0+2} L(d) = min{,0+1} L(e)=min{,0+1+1} L(c)=min{,0+2+3} L(e)=min{2,0+2+1} diff path

Choose v ∊ T with minimum L(v) =e

d.2

a,2

a.1

b,5

a z

b c

0

2

2

1

1

2

3

d e

1

Another Example: 4

Choose v ∊ T with minimum L(v)=z

d.2

a,2

e,4

a.1

b,5

LabelsL(b) = min{,0+2} L(d) = min{,0+1} L(e)=min{,0+1+1} L(c)=min{,0+2+3} L(e)=min{2,0+2+1} diff pathL(z)=min{,0+1+1+2}

Each node is labelled with its source node and the distance from the start node

Shortest path: a,d,e,z

a

f

d

5

2

e

7

4

Find shortest path a-f

2

7

10

6

b

c

3

a

f

d

5

2

e

7

4

Find shortest path a-f

a(0,a)

2

7

10

6

b

c

3

a

f

d

5

2

e

7

4

Find shortest path a-f

2

7

10

6

b

c

3

LabelsL(b) = min{,0+5} L(c) = min{,0+6}

Each node is labelled with its source node and the distance from the start node

a(0,a)

a

f

d

5

2

e

7

4

Find shortest path a-f

2

7

10

6

b

c

3

LabelsL(b) = min{,0+5} L(c) = min{,0+6} L(d) = min{,0+5+7} L(f) = min{,0+5+10}L(e) = min{,0+5+2}L(c) = min{,0+5+3}

Each node is labelled with its source node and the distance from the start node

a(0,a)

c

a

f

d

5

2

e

7

4

Find shortest path a-f

2

7

10

6

b

c

3

LabelsL(b) = min{,0+5} L(c) = min{,0+6} L(d) = min{,0+5+7} L(f) = min{,0+5+10}L(e) = min{,0+5+2}L(c) = min{,0+5+3}

Each node is labelled with its source node and the distance from the start node

a(0,a)

a

f

d

5

2

e

7

4

Find shortest path a-f

2

7

10

6

b

c

3

LabelsL(b) = min{,0+5} L(c) = min{,0+6} L(d) = min{,0+5+7} L(f) = min{,0+5+10}L(e) = min{,0+5+2}L(c) = min{,0+5+3}L(e) = min{,0+6+7}Each node is labelled with its source node and the distance from the start node

a(0,a)

a

f

d

5

2

e

7

4

Find shortest path a-f

2

7

10

6

b

c

3

LabelsL(b) = min{,0+5} –from aL(c) = min{,0+6} –from aL(d) = min{,0+5+7} –from bL(f) = min{,0+5+10} – from bL(e) = min{,0+5+2} –from bL(c) = min{6,0+5+3} –from bL(c) = min{6,0+5+2 +7} –from eL(f) = min{, 0+5+2 +4} – from ed not explored because (5+2+4)<12Shortest path: a,b,e,f

Length of path =11

Minimum

Paths

Graph Representation 1• Adjacency matrix• Rows and columns are

labeled with ordered vertices write a 1 if there is an edge between the row vertex and the column vertex and 0 if no edge exists between them

v w x y

v 0 1 0 1

w 1 0 1 1

x 0 1 0 1

y 1 1 1 0

Graph Representation 2

• Incidence matrix– Label rows with vertices– Label columns with edges– 1 if an edge is incident to a

vertex, 0 otherwise

e f g h j

v 1 1 0 0 0

w 1 0 1 0 1

x 0 0 0 1 1

y 0 1 1 1 0

Dijkstra Class Diagram

Arrays usedVertex [] vertexList;int[,] adjMat;DistOriginal [] sPath;Vertex [] vertexList;

Dijkstra by Michael McMillan

• Task• Using the code in the footnotes find all the

shortest paths in the following graph.

Task: Shortest Path in C#A=0(A) B=2(A) C=3(D) D=1(A) E=3(D) F=6(G) G=5(D)

Tasks: Shortest Path in C#

• Describe the role of each array.• Describe each class; methods, fields, variables.• Print out the full shortest path as follows• V1 — Dist1 — V2 —Dist2 — … Vn• Allow data to be input via a CSV file.• Make a Windows Application that uses a file

dialogue for the input file and outputs the shortest path in TextBox.

Directed Graphs

Summary: Procedural Programming

• Procedural or imperative programming includes:

• Variables• Types• Functions• Procedures• Control: sequence, iteration and condition• Simple data structures such as arrays.

Summary of Objects• Advantages of OO.• Understand basic OO program • Understand the difference between a class and an object;• Recognise that difference when reading Java code;• Understand what a constructor is and what type of code

should be placed inside it;• Create a simple object-oriented model that uses inheritance

to define some of the classes;• create public accessor and mutator methods to read and

change private variables; and

top related