1 / 77

Object Oriented Design

Object Oriented Design. In this lecture, we will introduce the basic notions of object oriented design We will examine some classes in the Java API and how they can be used In the next lecture, we will learn how objects are defined. Program Development.

marcoso
Télécharger la présentation

Object Oriented Design

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. Object Oriented Design • In this lecture, we will introduce the basic notions of object oriented design • We will examine some classes in the Java API and how they can be used • In the next lecture, we will learn how objects are defined

  2. Program Development • The creation of software involves four basic activities: • establishing the requirements • creating a design • implementing the code • testing the implementation • The development process is much more involved that this, but these basic steps are a good starting point

  3. Requirements • Requirements specify the tasks a program must accomplish (what to do, not how to do it) • They often address the user interface • An initial set of requirements are often provided, but usually must be critiqued, modified, and expanded • It is often difficult to establish detailed, unambiguous, complete requirements • Careful attention to the requirements can save significant time and money in the overall project

  4. Design • A program follows an algorithm, which is a step-by-step process for solving a problem • The design specifies the algorithms and data needed • The details of a specific algorithm may be expressed in pseudocode, which is code-like, but does not necessarily follow any specific syntax • example: compute average: • read numbers from user • for each number: • add to a sum variable, increment counter • output sum / counter

  5. Implementation • Implementation is the process of translating a design into source code • Most novice programmers think that writing code is the heart of software development, but it actually should be the least creative • Almost all important decisions are made during requirements analysis and design • Implementation should focus on coding details, including style guidelines and documentation

  6. Testing • A program should be executed multiple times with various input in an attempt to find errors • Debugging is the process of discovering the cause of a problem and fixing it • Programmers often erroneously think that there is "only one more bug" to fix • Tests should focus on design details as well as overall requirements

  7. The Waterfall Model Requirements Design Implementation Testing

  8. Introduction to Object-Oriented Design • The real world consists of object: students, houses, cars... • As human beings, we like to classify these objects and characterize them: • Dogs bark and like to eat bonzo • In general, politicians do not tell the truth • Triangles have three edges and sum of degrees 180 • Cars have gas and brake pedals, gear shift stick, steering wheel, ... If the gears are in reverse and you press the gas pedal, the car drives back.

  9. From Real-World objects to Software Objects • As in the real world, the design of sofwtare also involves processes such as identifying new classifications and characterizing them • A bank client has a credit profile which should have information on his personal earnings, real estate assets, savings etc. • A credit profile should be updated monthly and must have an estimation method • These new classifications also define objects, but this time they are software objects

  10. Software Objects • Just as the real world has objects, it is very useful to think of a software program as made of objects. • The objects in a software program are units which perform predefined tasks. • These units interact with eachother in a special manner, and this way the task can be accomplished. • A simple example: Display Text Program OutputWindow “Hello World”

  11. Real World vs. Software Objects • Sometimes software object model real world objects (bank account, client, form...) and sometimes other weird things (Logo turtle, output window, unix to unicode adaptor) • Note that real world objects do not necessarily represent tangible objects - they can refer to abstract notions (client profile) • As for software objects - they may sometimes represent tangible objects, but they generally do not • In general, software objects have a strong connection to real-world objects, and it’s helpful to think of them this way

  12. State and Behaviour • Software objects are characterized by two important things: • State: The object’s attributes • Behaviour: What the object can do, or what can be done with the object, and how the objects reacts • Examples: • A LOGO turtle has a location, current angle, the state of it tail (up/down). It can move forwards, move backwards, turn left, turn right, etc. • An Output Window has a location, size and a text it displays. One can append new text to the window, clear it, move it, resize it, close it, etc.

  13. State and Behaviour • The state of a software object is held in internal variables, or fields. • The behaviour of an object is represented by methods - which define the functionality of the object (what it can do, or what can be done with it): • moveForward(double units) • turnLeft(int degrees) • tailDown()

  14. Classes of Objects • All cars in the world have similar attributes (color, model, production year, license id, pedals, gear shift stick, etc...) and behaviour (driving) • Each car of many different cars can be identified by its own set of attributes • However, all cars are driven in the same way (more or less) • We say that there is a class of cars in the world, and each car is an object in this class, or: each car object is an instance (מופע)of the class car.

  15. Car Object Color = black Model = ford Prodution year = 1932 ... accelerate(int rate) brake() turnRight() turnLeft() changeGears() ... Car Object Color = red Model = suzuki Prodution year = 1997 ... accelerate(int rate) brake() turnRight() turnLeft() changeGears() ... Class Car Color Model Prodution year ... accelerate(int rate) brake() turnRight() turnLeft() changeGears() ... Car Object Color = off white Model = susita Prodution year = 1970 ... accelerate(int rate) brake() turnRight() turnLeft() changeGears() ...

  16. ... And in Software • A class is a description of objects having the same attributes and methods. • It can be thought of a blueprint (תבנית) for the object • A class defines the methods and state variables associated with an object • There can be many different objects of the same class, each having its own attributes. However, all objects conform to the same set of methods. • Example: you can open as many Output Windows as you want. But displaying text on all of them is done in the same manner.

  17. Instantiation & Initialization • The creation of a new object involves two things: creating an empty object and initializing its state. • Objects are always initialized when they are created. So the state of the object is always defined. • The creation of some objects requires information specifying their initial state. Other require no such information. • Example: A LOGO Turtle does not require any information for its creation. We will see other objects that require information later.

  18. Creating New Objects • We use the operator new to create objects: new Turtle(); new InputRequestor(); new Student(“Jimi”,”Biology”,2); • The operator new is followed by the name of the class from which we want to create a new instance, followed by a pair of parenthesis. If the creation requires parameters, we write them inside the parenthesis.

  19. References • Objects live in the main memory. • When an object is created it is allocated a block of memory sufficient to hold all its state variables. The object occupies this block until it is destroyed. • We have no control on the location in memory, where an object is created. It is just created somewhere. • In order to interact with an object, we must have some way to refer to it. • We refer to an object by means of an objectreference.

  20. References • An object reference is a special kind of value that identifies an object. • Object references can be stored in variables. Turtle leonardo = new Turtle(); Student jimi = new Student(“Jimi”,”Biology”,2); • The variable hold the reference to a particular object. It refers to this object. We can interact with the object through a variable that refers to it.

  21. References • The declaration of the object referencevariable and the creation of the object can be separate activities. • We declare a variable named leonardo whose type is ‘a reference to Turtle’: Turtle leonardo; • leonardo can store a reference to an instance of class Turtle. However, no Turtle object is created yet and the value of leonardo is undefined!

  22. References • We now create a new Turtle object and store the reference to it in the variable leonardo: leonardo = new Turtle(); • In a later stage of the program, leonardo can be set to refer to another object, but it can only refer to a Turtle object. • There is a special null value that can be assigned to any reference variable to denote that this variable does not refer (currently) to any object. leonardo = null;

  23. Methods • We interact with an object by means of method invocation: Turtle leonardo = new Turtle(); leonardo.turnLeft(90); leonardo.moveForwards(100); • Some methods have return values: InputReader in = new InputReader(); int x = in.readInt (“Please enter a number”);

  24. References • An object reference holds the memory address of an object ChessPiece bishop1 = new ChessPiece(“black”); bishop1

  25. References ChessPiece bishop1 = new ChessPiece(“black”); ChessPiece bishop2 = new ChessPiece(“white”); bishop2 bishop1

  26. Before After bishop1 bishop2 bishop1 bishop2 Reference Assignment • For object references, the value of the memory location is copied: bishop2 = bishop1;

  27. Reference Assignment bishop2 = bishop1; System.out.println (bishop2.getColor()); // prints “black” bishop2 bishop1

  28. Before After num1 num2 num1 num2 5 12 5 5 Assignment of Primitive Types • The act of assignment takes a copy of a value and stores it in a variable • For primitive types: num2 = num1;

  29. Aliases • Two or more references that refer to the same object are called aliases of each other • There is only one copy of the object (and its data), but with multiple ways to access it • Aliases can be useful, but should be managed carefully • Affecting the object through one reference affects it for all aliases, because they refer to the same object

  30. Garbage Collection • When an object no longer has any valid references to it, it can no longer be accessed by the program • It is useless, and therefore called garbage • Java performs automatic garbage collection periodically, returning an object's memory to the system for future use • In other languages, the programmer has the responsibility for performing garbage collection

  31. Class Libraries • The Java API is a class library, a group of classes that support program development, and offer a wide variety of services • The Java API is separated into packages • Each package contains a set of classes that relate in some way • The System class, for example, is in package java.lang

  32. The Java API Packages • Some packages in the Java API: java.applet java.awt java.beans java.io java.lang java.math java.net java.rmi java.security java.sql java.text java.util

  33. Importing Packages • Using a class from the Java API can be accomplished by using its fully qualified name: java.lang.System.out.println(); • Or, the package can be imported using an import statement, which has two forms: import java.applet.*; import java.util.Random; • The java.lang package is automatically imported into every Java program

  34. Example: The String Class • A character string in Java is an object, defined by the String class String name = new String ("Ken Arnold"); • Because strings are so common, Java allows an abbreviated syntax: String name = "Ken Arnold"; • Once a String object is created, it cannot change its value. Strings are immutable objects.

  35. Some Useful Methods in String • charAt(int index) • indexOf(char ch) • lastIndexOf(char ch) • startsWith(String suffix) • lastIndexOf(char ch) • length() • ...See the API!

  36. String sentence = “Houston, we have a problem.”; int length = sentence.length(); // length=27 String word = sentence.substring(0,7); // word = “Houston” word = word.toLowerCase(); // word = “houston”; char c = word.charAt(2); // c=‘u’ boolean b = word.equals(“Houston”); // b=false int index = sentence.indexOf(“we”); word = sentence.substring(index, index+3); // word=“we “ word = word.trim(); // word=“we”

  37. class StringTest { public static void main (String[] args) { String str1 = "Seize the day"; String str2 = new String(); String str3 = new String (str1); String str4 = "Day of the seize"; String str5 = "Seize the day"; String str6 = new String(“Seize the day”); System.out.println ("str1: " + str1); System.out.println ("str2: " + str2); System.out.println ("str3: " + str3); System.out.println ("str4: " + str4); System.out.println ("str5: " + str5); System.out.println();

  38. System.out.println ("Length of str1: " + str1.length()); System.out.println ("Length of str2: " + str2.length()); System.out.println(); System.out.println ("Index of 'e' in str4: " + str4.indexOf('e')); System.out.println ("Last index of 'e' in str4: " + str4.lastIndexOf('e')); System.out.println ("The character at position 3 in str1: " + str1.charAt(3)); System.out.println ("The substring of str1 from " + "position 6 to position 8: " + str1.substring(6, 9)); System.out.println(); if (str1 == str5) System.out.println ("str1 and str5 refer " + "to the same object."); if (str1 != str3) System.out.println ("str1 and str3 do NOT refer " + "to the same object."); if (str1.equals(str3)) System.out.println ("str1 and str3 contain the same “ + “characters."); System.out.println();

  39. str2 = str1.toUpperCase(); System.out.println ("str2 now refers to: " + str2); if (str1.equalsIgnoreCase(str2)) System.out.println ("str1 and str2 contain the same " + "characters (ignoring case)."); str5 = str1.replace('e', 'X'); System.out.println ("str5 now refers to: " + str5); System.out.println(); System.out.println ("str1 starts with \"Seize\": " + str1.startsWith("Seize")); System.out.println ("Creating a string from a number: " + String.valueOf(22+33+44)); } // method main } // class Carpe_Diem

  40. The Output str1: Seize the day str2: str3: Seize the day str4: Day of the seize str5: Seize the day Length of str1: 13 Length of str2: 0 Index of ‘e’ in str4: 9 Last index of ‘e’ in str4: 15 The character at position 3 in str1: z The substring of str1 from position 6 to position 8: the str1 and str5 refer to the same object str1 and str3 do NOT refer to the same object str1 and str3 contain the same characters

  41. The Output (cont). str2 now refers to: SEIZE THE DAY str1 and str2 contain the same characters (ignoring case) str5 now refers to SXizX thX day str1 starts with “Sieze”: true Creating a string from a number: 99

  42. The String Lesson • We do not need to know the implementation of an object to use it - we only need the interface • The interface and the implementation are defined by a class • Many instances - objects - of the same class can be created • These instances differ by their state • It is possible to have two different instances of the same class with the same state

  43. The String Lesson (cont.) • Just as in primitive data types, an object must be initialized • There could be several ways to initialize an object

  44. Yet Another Example - The Random class • The need to use random numbers occurs frequently in software (simulations, games, ...) • Real random numbers cannot be generated on a computer • A pseudo-random number generator: • pick a random seed • first number is a function of the seed • each number is a function of the last

  45. The Random Class • Defined in the java.util package • Implements a pseudo-random number generator • Useful methods: • nextInt() - random integer across the entire int spectrum • nextFloat() - a random float between 0 and 1 • Dice: Random dice = new Random(); int roll = Math.abs(dice.nextInt()) % 6 + 1;

  46. The Random Class Expression Math.abs (rand.newInt()) % 6 + 1 Math.abs (rand.newInt()) % 10 + 1 Math.abs (rand.newInt()) % 101 Math.abs (rand.newInt()) % 11 + 20 Math.abs (rand.newInt()) % 11 - 5 Range 1 to 6 1 to 10 0 to 100 20 to 30 -5 to 5

  47. import java.util.*; class Flip { public static void main (String[] args) { Random coin = new Random(); int count = 0, heads = 0, tails = 0; int number_flips, flip_result; InputReader in = new InputReader(); OutputWindow out = new OutputWindow(); in.readInt(“Please enter the number of flips”); while (count < number_flips) { flip_result = Math.abs (coin.nextInt()) % 2; if (flip_result == 0) heads = heads + 1; else tails = tails + 1; count = count + 1; } out.println ("heads = " + heads + “ tails = “ + tails); } // method main } // class Flip

  48. The StringBuffer Class • String class manages the use of immutable strings, i.e., they cannot change their size or content • The StringBuffer class allows to use dynamic strings - which can be modified • append(char c) • insert(int index, char c) • charAt(int index) • setCharAt(int index, char c) • reverse() • length()

  49. class StringBufferTest { public static void main (String[] args) { StringBuffer text1 = new StringBuffer(); StringBuffer text2 = new StringBuffer(“ m”); StringBuffer text3 = new StringBuffer(“1 dollar”); text1.append(1); text1.append(“ p”); text1.append(‘e’); text1.append(‘n’); text1.append(“ny”); text2.insert(0,1); text2.insert(2,”di”); text2.insert(5,’e’); System.out.println(text1); System.out.println(text2); System.out.println(text3); text3.reverse(); System.out.println(text3); } }

  50. Output: 1 penny 1 dime 1 dollar rallod 1

More Related