870 likes | 1k Views
DT265-2 Object Oriented Software Development 2 Lecture 2 : Revision. Lecturer Pat Browne p atrick.browne@dit.ie. A Programming Paradigm.
E N D
DT265-2 Object Oriented Software Development 2Lecture 2 : Revision Lecturer Pat Browne patrick.browne@dit.ie
A Programming Paradigm • Object-oriented programming is frequently referred to as a programmingparadigm. 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.
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 • An object oriented system is structured as a community of interacting agents, called objects. Each object has a role to play. Eachobject provides a service, or performs an action, that is used by othermembers of the community.
Messages and Methods • The chain reaction that ultimately resulted in the solution to Chris's requirement for flowersbegan 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'sfriend Robin. The members of this community interact witheach 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 HierarchiesInheritance • 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.
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 accompaniedby any additional information (arguments) needed to carry out therequest. The receiver is the object to whom the message is sent. Ifthe receiver accepts the message, it accepts the responsibility to carryout the indicated action. In response to a message, the receiver willperform some method to satisfy the request.
Messages and Methods • Note the important principle of information hiding in regard tomessage passingthat is, the client sending the request need not know the actualmeans by which the request will be honoured.
Messages and Methods • There is another principle implicit in message passing. If there is a task toperform, the first thought of the client is to findsomebody else he or she canask to do the work. • An important partof object-oriented programming is the development of reusable components, andan important first step in the use of reusable components is a willingness to trustsoftware written by others (e.g. e-voting).
Objects and messages A single Object A set of object and messages A single Object A single Object receiving a message
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.
Account public 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 Demo class 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 Account class 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);}}
Run Park public class RunPark { //Creates a new Park object. public static void main(String args[]) { Park myPark = new Park();}}
Park public 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 Area public 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(); } }
Path public class Path { // ------- Constructor ---------- // Creates a new path. public Path() { System.out.println("The builders have just finished laying the path"); } }
Tree.1 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.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 + ")"); } }
New Plant super class public 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-class public 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; }}
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.
Stack Code.1 public class Stack { // private data to hold stack state private int top; private int[] storage; // constructor Stack(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.2 int pop() { top--; return storage[top+1];} boolean isEmpty() { return (top == -1);} } // end of class // The example program contains a main() method