This document provides an overview of object-oriented programming concepts including classes, objects, encapsulation, abstraction, inheritance, and polymorphism. It discusses different programming languages like Java and C++ that use the object-oriented paradigm. Specific concepts covered include defining classes with attributes and methods, creating object instances of classes, encapsulating data within classes, and abstract data types. Examples are provided to illustrate classes like Account and Circle and their corresponding objects.
Gen AI in Business - Global Trends Report 2024.pdf
Lecture 1 uml with java implementation
1. COSC 1320 Please find your perfect seat first 3 rows,you will sit there this June! Please find your perfect seat first 3 rows,you will sit there this June! Please find your perfect seat first 3 rows,you will sit there this June! tlc2 / Ewe2010! www.uh.edu/webct psid/ mmddyya!
2. Introduction to Computer Science II COSC 1320/6305 Lecture 1: Software Engineering and Classes UML, OOA/OOD/JAVA Implementation A TOP DOWN EXAMPLE (Chapter 12)
5. Software Engineering Software Engineering is the study of the techniques and theory that support the development of high-quality software The focus is on controlling the development process to achieve consistently good results We want to: satisfy the client – the person or organization who sponsors the development meet the needs of the user – the people using the software for its intended purpose
6. Goals of Software Engineering Solve the right problem more difficult than it might seem client interaction is key Deliver a solution on time and under budget there are always trade-offs Deliver a high-quality solution beauty is in the eye of the beholder we must consider the needs of various stakeholders
8. Development Models A development life cycle defines a process to be followed during product development Many software development models have been introduced All of them address the following fundamental issues in one way or another: problem analysis (What?) design (How?) implementation evaluation maintenance
9. Problem Analysis - What We must specify the requirements of the software system
10. Problem Analysis - What We must specify the requirements of the software system Must be based on accurate information Various techniques: discussions and negotiations with the client modeling the problem structure and data flow observation of client activities analysis of existing solutions and systems
11. Design - How We must specify the solution You would not consider building a bridge without a design Design involves determining: the overall software structure (architecture) the key objects, classes, and their relationships Alternatives should be considered
12. Implementation We must turn the design into functional software Too many people consider this the primary act of software development May involve the reuse of existing software components
13. Evaluation We must verify that the system conforms to the requirements This includes, but goes way beyond, testing code with test cases It is possible to build a system that has no bugs and yet is completely wrong
14. Maintenance After a system is initially developed, it must be maintained This includes: fixing errors making enhancements to meet the changing needs of users The better the development effort, the easier the maintenance tasks will be
15. The Waterfall Model One of the earliest development models Each stage flows into the next Driven by documentation Advantages: Lays out clear milestones and deliverables Has high visibility – managers and clients can see the status Disadvantages: late evaluation not realistic in many situations
16. The Spiral Model Developed by Barry Boehm in the mid '80s Embraces an iterative process, where activities are performed over and over again for different aspects of the system Designed to reduce the risks involved Continually refines the requirements Each loop through the spiral is a complete phase of development
17. The Evolutionary Model*** Like the spiral model, an evolutionary approach embraces continual refinement Intermediate versions of the system are created for evaluation by both the developers and the client May be more difficult to maintain depending on the attention given to the iterations
18. The Unified Modeling Language The Unified Modeling Language (UML) has become a standard notation for software analysis (OOA) & design (OOD) It is language independent It includes various types of diagrams (models) which use specific icons and notations However, it is flexible – the details you include in a given diagram depend on what you are trying to capture and communicate
25. Objectives Advise on the class Software Engineering Problem solving Memory Classes
26. Life Cycle “Read a sequence of marks from the user, ending with the word ‘done’ and then print the average of the marks.”
27. Specify — Design — Code — Test Edit—Compile—Run cycle: Problem Solving InitialDesign Edit: typing in the Java code Specification Compile: Translating to executable instructions Run: Testing the program to see that it works
28. Life Cycle Problem ⇒Specification ⇒ Design of Solution ⇒ Computer program ⇒ Test and debug! “Find the average mark in an exam” “Read a sequence of marks from the user, ending with the word ‘done’ and then print the average of the marks.”
29. Life Cycle Problem ⇒ Problem description ⇒Design of Solution ⇒ Computer program ⇒ Test and debug “Initialise count and sum loop: Prompt user for next number if user enters a non-number, then exit loop read the number, and add to the sum increment the count end loop print out the value of sum/count” pseudocode
30. Life Cycle ⇒ Problem description ⇒ Design of Solution ⇒Computer program ⇒ Test and debug import java.util.*; public class ExamAverage { public void findAverage () { int count = 0; double sum = 0; Scanner input = newScanner(System.in); while (true) { System.out.print("Enter next mark: "); if ( ! input.hasNextDouble() ) break; sum = sum + input.nextDouble(); count = count + 1; } System.out.printf(“average mark = %4.2f", sum/count); } }
31. Life Cycle ⇒ Problem description ⇒ Design of Solution ⇒ Computer program ⇒Test and debug: Run the program on a range of possible inputs and check that it is correct. Enter next mark: 70 Enter next mark: 85 Enter next mark: 65 Enter next mark: done average mark = 73.33 Enter next mark: done Error: divide by zero
32. Objectives Advise on the class Software Engineering Problem solving Memory Classes
33. Machine Languages, Assembly Languages, and High-level Languages Three types of programming languages Machine languages Strings of numbers giving machine specific instructions Example: +1300042774 +1400593419 +1200274027 Assembly languages English-like abbreviations representing elementary computer operations (translated via assemblers) Example: LOAD BASEPAY ADD OVERPAY STORE GROSSPAY High-level languages Codes similar to everyday English Use mathematical notations (translated via compilers) Example: grossPay = basePay + overTimePay
34. History of C C Evolved by Ritchie from two previous programming languages, BCPL and B Used to develop UNIX Used to write modern operating systems Hardware independent (portable) By late 1970's C had evolved to "Traditional C“ Standardization Many slight variations of C existed, and were incompatible Committee formed to create a "unambiguous, machine-independent" definition Standard created in 1989, updated in 1999
35. The C Standard Library C programs consist of pieces/modules called functions A programmer can create his own functions Advantage: the programmer knows exactly how it works Disadvantage: time consuming Programmers will often use the C library functions Use these as building blocks Avoid re-inventing the wheel! If a premade function exists, generally best to use it rather than rewrite Library functions carefully written, efficient, and portable
36. The Key Software Trend: Object Technology Objects Reusable software componentsthat model items in the real world Meaningful software units Date objects, timeobjects, paycheckobjects, invoiceobjects, audio objects, videoobjects, file objects, recordobjects, etc. Any noun can be represented as an object! More understandable, better organized, and easier to maintain than procedural programming Favor modularity
37. C++ C++ Superset of C developed by BjarneStroustrup at Bell Labs "Spruces up" C, and provides object-oriented capabilities Object-oriented very powerful 10 to 100 fold increase in productivity Dominant language in industry and academia
38. Java Java is used to Create Web pages with dynamic and interactive content Develop large-scale enterprise applications Enhance the functionality of Web servers Provide applications for consumer devices (such as cell phones, pagers and personal digital assistants)
39. Other High-level Languages Other high-level languages FORTRAN Used for scientific and engineering applications COBOL Used to manipulate large amounts of data Pascal Intended for academic use
40. Basics of a Typical C Program Development Environment Preprocessor program processes the code. Compiler creates object code and storesit on disk. Compiler Linker links the object code with the libraries Primary Memory Loader Loader puts program in memory. Primary Memory CPU takes each instruction and executes it, possibly storing new data values as the program executes. CPU Preprocessor Linker Editor Disk Disk Disk Disk Disk . . . . . . . . . . . . Phases of C++ Programs: Edit Preprocess Compile Link Load Execute Program is created in the editor and stored on disk.
41. Memory Concepts Variable names Correspond to actual locations in computer's memory Every variable has name, type, size and value When new value placed into variable, overwrites previous value Reading variables from memory nondestructive
42. Memory Concepts 45 45 72 45 72 integer1 integer1 integer2 integer1 integer2 117 sum std::cin >> integer1; Assume user entered 45 std::cin >> integer2; Assume user entered 72 sum = integer1 + integer2;
43. Memory 9278 9279 9280 9281 9282 9283 9284 9285 9286 Main memory is divided into many memory locations (or cells) Each memory cell has a numeric address, which uniquely identifies it
44. Storing Information Each memory cell stores a set number of bits (usually 8 bits, or one byte) Large values are stored in consecutive memory locations 9278 9279 9280 9281 9282 9283 9284 9285 9286 10011010
45. References 38 num1 "Steve Jobs" name1 Note that a primitive variable contains the value itself, but an object variable contains the address of the object An object reference can be thought of as a pointer to the location of the object Rather than dealing with arbitrary addresses, we often depict a reference graphically
46. Assignment Revisited 38 num1 Before: 96 num2 38 num1 After: 38 num2 The act of assignment =takes a copy of a value and stores it in a variable For primitive types: num2 = num1;
48. Numeric Primitive Data Type byte short int long float double Storage 8 bits 16 bits 32 bits 64 bits 32 bits 64 bits Min Value -128 -32,768 -2,147,483,648 < -9 x 1018 +/- 3.4 x 1038 +/- 1.7 x 10308 Max Value 127 32,767 2,147,483,647 > 9 x 1018 The difference between the various numeric primitive types is their size, and therefore the values they can store: 9278 9279 9280 9281 9282 9283 9284 9285 9286
54. Software: User Programs Programs that are neither OS programs nor applications are called user programs. User programs are what you’ll be writing in this course.
55. Putting it all together Disk RAM CPU Cache OS App Bus Programs and applications that are not running are stored on disk.
56. Putting it all together Disk RAM CPU Cache OS App App OS Bus When you launch a program, the OS controls the CPU and loads the program from disk to RAM.
57. Putting it all together Disk RAM CPU Cache OS App App App Bus The OS then relinquishes the CPU to the program, which begins to run.
58. The Fetch-Execute Cycle As the program runs, it repeatedly fetches the next instruction (from memory/cache), executes it, and stores any results back to memory. Disk RAM CPU Cache OS App App App Bus That’s all a computer does: fetch-execute-store, millions of times each second!
60. Overview Understand Classesand Objects. Understand some of the key concepts/features in the Object Oriented paradigm. Benefits of Object Oriented paradigm.
61. OOP: Model, map, Reuse, extend Model the real world problem to user’s perceive Use similar metaphor in computational env. Construct Reusable components Create new components from existing ones.
64. Object Oriented Paradigm: Features Encapsulation Data Abstraction Single Inheritance OOP Paradigm Polymorphism Persistence Delegation Genericity Multiple Inheritance
65. Java’s OO Features Encapsulation Data Abstraction Single Inheritance Java OOP Paradigm Polymorphism Persistence Delegation Genericity Multiple Inheritance
66. Encapsulation Associates the Code & the Datait manipulates into a single unit; and keeps them safe from external interference and misuse. Encapsulation Data Abstraction Single Inheritance OOP Paradigm Polymorphism Persistence Delegation Data Genericity Code Multiple Inheritance
67. Data Abstraction The technique of creating new data types that are well suited to an application. It allows the creation of user defined data types, having the properties of built data types and a set of permitted operators. In Java, partial support. In C++, fully supported (e.g., operator overloading). Encapsulation Data Abstraction Single Inheritance OOP Paradigm Polymorphism Persistence Delegation Genericity Multiple Inheritance
68. Abstract Data Type (ADT) A structure that contains both dataand the actions to be performed on that data. Classis an implementation of an Abstract Data Type.
70. Class - Example class Account { private StringaccountName; privatedoubleaccountBalance; publicwithdraw(); publicdeposit(); public determineBalance(); } // Class Account
71. Class Class is a set of attributesand operations that are performed on the attributes. Student Circle Account accountName accountBalance name age studentId centre radius withdraw() deposit() determineBalance() area() circumference() getName() getId()
72. Objects An Object Oriented system is a collection of interacting Objects. Objectis an instance of a class.
73. Classes /Objects John and Jill are objects of class Student :John Student :Jill :circleA circleA and circleB are objects of class Circle Circle :circleB
74. Class A class represents a template for several objects that have common properties. A class defines all the properties common to the object - attributes and methods. A class is sometimes called the object’s type.
75. Object Objects have state and classes don’t. Johnis an object (instance) of class Student. name = “John”, age = 20, studentId = 1236 Jill is an object (instance) of class Student. name = “Jill”, age = 22, studentId = 2345 circleAis an object (instance) of class Circle. centre = (20,10), radius = 25 circleB is an object (instance) of class Circle. centre = (0,0), radius = 10
76. Encapsulation All information (attributes and methods) in an object oriented system are stored within the object/class. Information can be manipulated through operations performed on the object/class– interface to the class. Implementation is hidden from the user. Objectsupport Information Hiding – some attributes and methods can be hidden from the user.
77. Encapsulation - Example message withdraw deposit account Balance message determine Balance message class Account { privatedoubleaccountBalance; public withdraw(); public deposit(); public determineBalance(); } // Class Account
78. Data Abstraction The technique of creating new data types that are well suited to an application. It allows the creation of user defined data types, having the properties of built in data types and more.
79. Abstraction - Example class Account { private String accountName; private double accountBalance; public withdraw(); public deposit(); public determineBalance(); } // Class Account Creates a data type Account AccountacctX;
80. Inheritance Parent Child New data types (classes) can be defined as extensions to previously defined types. Parent Class (Super Class) – Child Class (Sub Class) Subclass inherits properties from the parent class. Inheritedcapability
81. Inheritance - Example Examples Define Person to be a class A Person has attributes, such as age, height, gender Assign values to attributes when describing object Define student to be a subclass of Person A studenthas all attributes of Person, plus attributes of his/her own ( student no, course_enrolled) A studenthas all attributes of Person, plus attributes of his/her own (student no, course_enrolled) A studentinherits all attributes of Person Define lecturer to be a subclass of Person lecturer has all attributes of Person, plus attributes of his/her own (staff_id, subjectID1, subjectID2)
82. Inheritance - Example Circle Class can bea subclass (inheritedfrom) of a parent class - Shape Shape Circle Rectangle
83. Inheritance - Example Inheritance can also have multiple levels. Shape Circle Rectangle GraphicCircle
84. Uses of Inheritance - Reuse If multiple classes have common attributes/methods, these methods can be moved to a common class - parent class. This allows reuse since the implementation is not repeated. Example : Rectangle and Circle method have a common method move(), which requires changing the center coordinate.
85. Uses of Inheritance - Reuse Circle centre radius area() circumference() move(newCentre) move(newCentre) { centre = newCentre; } Rectangle centre height width area() circumference() move(newCentre) move(newCentre){ centre = newCentre; } move(newCentre) { centre = newCentre; }
86. 86 Uses of Inheritance - Reuse Shape centre move(newCentre) { centre = newCentre } area() circumference() move(newCentre) Rectangle Circle height width radius area() circumference() area() circumference()
87. Uses of Inheritance - Specialization Specialized behavior can be added to the child class. In this case the behaviour will be implemented in the child class. e.g. the implementation of area() method in the Circle class is different from the area() method in the Rectangle class. area() method in the child classes override the method in parent classes().
88. 88 Circle centre radius area() circumference() move(newCentre) area() { return pi*r^2; } Uses of Inheritance - Specialization Rectangle centre height width area() circumference() move(newCentre) area() { return height*width; }
89. 89 Uses of Inheritance - Specialization area() { return pi*r^2; } Shape centre area(); - not implemented and left for the child classes to implement area() circumference() move(newCentre) Rectangle Circle height width radius area() circumference() area() { return height*width; } area() circumference()
90. Uses of Inheritance – Common Interface All the operations that are supported for Rectangle and Circle are the same. Some methods have common implementation and others don’t. move() operation is common to classes and can be implemented in parent. circumference(), area() operations are significantly different and have to be implemented in the respective classes. The Shape class provides a common interface where all 3 operations move(), circumference() andarea().
91. Uses of Inheritance - Extension Extend functionality of a class. Child class adds new operations to the parent class but does not change the inherited behavior. e.g. Rectangle class might have a special operation that may not be meaningful to the Circle class - rotate90degrees()
92. Uses of Inheritance - Extension Shape centre area() circumference() move(newCentre) Rectangle Circle height width radius area() circumference() rotate90degrees() area() circumference()
93. Uses of Inheritance – Multiple Inheritance Inherit properties from more than one class. This is called Multiple Inheritance. Shape Graphics Circle
94. Uses of Multiple Inheritance This is required when a class has to inherit behavior from multiple classes. In the example Circle class can inherit move() operation from the Shape class and the paint() operation from the Graphics class. Multiple inheritance is not supported in JAVA but is supported in C++.
95. Uses of Inheritance – Multiple Inheritance Shape centre area() circumference() move(newCentre) Circle radius area() circumference() GraphicCircle color paint()
96. Polymorphism Polymorphic which means “many forms” has Greek roots. Poly – many Morphos - forms. In OO paradigm polymorphism has many forms. Allow a single object, method, operator associated with different meaning depending on the type of data passed to it.
97. Polymorphism An object of type Circle or Rectangle can be assigned to a Shapeobject. The behavior of the object will depend on the object passed. circleA = new Circle(); Create a new circle object Shape shape = circleA; shape.area(); area() method for circle class will beexecuted rectangleA = new Rectangle(); Create a new rectangle object shape= rectangleA; shape.area()area() method for rectangle will be executed.
98. Polymorphism – Method Overloading Multiple methods can be defined with the same name, different input arguments. Method 1 - initialize(int a) Method 2 - initialize(int a, int b) Appropriate method will be called based on the input arguments. initialize(2) Method 1 will be called. initialize(2,4) Method 2 will be called.
99. 99 Polymorphism – Operator Overloading Allows regular operators such as +, -, *, / to have different meanings based on the type. e.g. + operator for Circle can re-defined Circle c = c + 2; Not supported in JAVA. C++ supports it.
100. 100 Persistence The phenomenon where the object outlives the program execution. Databases support this feature. In Java, this can be supported if users explicitly build object persistency using IO streams.
101. 101 Why OOP? Greater Reliability Break complex software projects into small, self-contained, and modular objects Maintainability Modular objects make locating bugs easier, with less impact on the overall project Greater Productivity through Reuse! Faster Design and Modelling
102. Benefits of OOP.. Inheritance: Elimination of Redundant Code and extend the use of existing classes. Build programs from existing working modules, rather than having to start from scratch. save development time and get higher productivity. Encapsulation: Helps in building secure programs.
103. Benefits of OOP.. Multiple objects to coexist without any interference. Easy to mapobjects in problem domain to those objects in the program. It is easy to partition the work in a project based on objects.
104. Benefits of OOP.. Object Oriented Systems can be easily upgraded from small to large systems. Message-Passing technique for communication between objects make the interface descriptions with external systems much simpler. Software complexity can be easily managed.
105. Summary Object Oriented Analysis, Design, and Programming is a Powerful paradigm Enables Easy Mapping of Real world Objects to Objects in the Program This is enabled by OO features: Encapsulation Data Abstraction Inheritance Polymorphism Persistence Standard OO Analysis and Design (UML) and Programming Languages (C++/Java) are readily accessible.
107. Differences Between Procedural Programming (PP) and Object Oriented Programming (OOP) The focus of procedural programming is to break down a programming task into a collection of variables, functionsand modules, whereas in object oriented programming it is to break down a programming task into objectswith each "object" encapsulating its own data (variables) and methods (functions). We will sometimes use predefined classes and sometimes write our own classes. OOP PP Variables Data Functions Methods Class
111. Example program, OOP in Java 7-111 The core of OOP: “Put related things together.” Design Implement Circle.java public class Circle { private double radius; static double PI = 3.14; publicCircle(double r) { radius = r; } double getPerimeter() { return 2 * PI * radius; } } CLASS Participation B! Main.java public classMain { public static void main(String[] args) { Circle circle = new Circle(10); System.out.println("Circle Perimeter " + circle.getPerimeter()); } } Data OOP Methods
115. Start with OOA&OOD or Coding? The heart of object-oriented problem solving is the construction of a model. Architects design buildings. Builders use the designs to create buildings. Blueprintsare the standard graphical language that both architects and builders must learn as part of their trade. Writing software is not unlike constructing a building. Writing software begins with the construction of a model. A model is an abstraction of the underlying problem. Unified Modeling Language (UML) is a pictorial language used to makesoftware blueprints. “A picture is worth a thousand words”
116. OOAnalysis & Design: UML Unified Modeling Language (UML) is a standardized general purpose modeling language in the field of software engineering. UML includes a set of graphical notation techniques to create visual models of software intensive systems. UML is not a programming language but tools can be used to generate code in various languages using UML diagrams. UML has a direct relation with object oriented analysis and design. The most important purpose of object oriented (OO) analysis is to identify objects of a system to be designed. After identifying the objects their relationships are identified and finally the design is produced.
117. Unified Modeling Language UMLprovides structure for problem solving. A method for modeling object oriented programs. A means for visualizing, constructing and documenting software projects. Promotes component reusability. You will not understand what your algorithm does two weeks after you wrote it. But if you have the model, you will catch up fast and easily. Teamwork for parallel development of large systems. UMLincludes 13 diagrams.
118. 1. UML Use Case Diagrams The use case diagram is the first model when starting a project. A use case is a set of scenarios that describing an interaction between a user and a system. The emphasis is on what a system does rather than how. Use Case Diagram displays the relationship among actors (users) and use cases (scenarios ). Use cases are used during the analysis phase of a project to identify and to partition system functionality. The two main components of a use case diagram are use cases and actors. An actor is represents a user or another system that will interact with the system you are modeling. Use cases describe the behavior of the system when one of these actors perform a task.
119. 1. UML Use Case Diagrams We first write use cases, and then we draw them. For example, here is a typical use case for a point of sale system. Here is just ONE USE CASE from this system 1. Cashier swipes product over scanner, scanner reads UPC code. 2. Price and description of item, as well as current subtotal appear on the display facing the customer. The price and description also appear on the cashier’s screen. 3. Price and description are printed on receipt. 4. System emits an audible “acknowledgement” tone to tell the cashier that the UPC code was correctly read. Clearly a point of sale system has many more use cases than this. Use Case 1: Check Out Item
120. 1. Use Case Diagrams Drawing Use Case Diagrams 1. Cashier swipes product over scanner, scanner reads UPC code. 2. Price and description of item, as well as current subtotal appear on the display facing the customer. The price and description also appear on the cashier’s screen. 3. Price and description are printed on receipt. 4. System emits an audible “acknowledgement” tone to tell the cashier that the UPC code was correctly read. Inside the boundary rectangle we see the use cases. These are the ovals with names inside. The lines connect the actors to the use cases that they stimulate. Use Case 1: Check Out Item Use Case 1 Use Case 2 Use Case 3 Use Case 4
121. 2. UMLClass Diagrams The purpose of a class diagram is to depict the classes within a model. A class diagram gives an overview of a system by showing its classes and the relationships among them. In an object oriented application, classes have attributes(member variables), operations (member methods/functions) and relationships with other classes. The fundamental element of the class diagram is an icon the represents a class. A class icon is simply a rectangle divided into 3 compartments. The topmost compartment contains the name of the class. The middle compartment contains a list of attributes (member variables), and the bottom compartment contains a list of operations(member methods/functions). In many diagrams, the bottom two compartments are omitted. Even when they are present, they typically do not show every attributeand operations. The goal is to show only those attributesandoperations that are useful for the particular diagram. The central class is the Order. Associated with it are the Customer making the purchase and the Payment. A Payment is one of three kinds: Cash, Check, or Credit. The order contains OrderDetails (line items), each with its associated Item.
122. 2. UML Class Diagrams Notice that each member variable is followed by a colon and by the type of the variable. Notice also that the return values follow the member methods/functions in a similar fashion. Finally, notice that the member function arguments are just types. Again, these can be omitted if they are redundant...
123. 2. UML Class Diagrams Class diagrams also display relationships among classes . Each instance of type Circle seems to contain an instance of type Point. This is a relationship known as composition. It can be depicted in UML using a class relationship. The black diamond represents composition. It is placed on the Circle class because it is the Circle that is composed of a Point. The arrowhead on the other end of the relationship denotes that the relationship is navigable in only one direction. That is, Point does not know about Circle. But, Circle knows about Point. The arrow lets you know who "owns" the association's implementation. At the code level, this implies a NOimport Circle.java within Point.java BUT, this also implies a import Point.java within Circle.java In UMLrelationships are presumed to be bidirectional unless the arrowhead is present to restrict them.
124. 2. UML Class Diagrams Composition relationships (black diamond) are a strong form of aggregation. Aggregation is a whole/part relationship. In this case, Circle is the whole, and Point is part of Circle . Composition also indicates that the lifetime of Point is dependent upon Circle. This means that if Circle is destroyed, Point will be destroyed with it. In this case we have represented the composition relationship as a member variable.
125. 2. UML Class Diagrams The weak form of aggregation is denoted with an open diamond. This relationship denotes that the aggregate class (the class with the white diamond touching it) is in some way the “whole”, and the other class in the relationship is somehow “part” of that whole. Window class containsmany Shape instances. In UML the ends of a relationship are referred to as its “roles”. Notice that the role at the Shape end of the aggregation is marked with a “*” (multiplicity). Multiplicity denotes the number of objects that can participate in the relationship. Notice also that the role has been named. This is the name of the instance variable within Window that holds all the Shapes.
126. 2. UML Class Diagrams Another common relationship in class diagrams is a generalization. A generalization is used when two classes are similar, but have some differences. In other words, it shows the inheritance relationship . The inheritance relationship (generalization) in UML is depicted by a peculiar triangular arrowhead. In this diagram we see that Circle and Square (derived classes) both derive from Shape (base class/super class). Circle and Square(derived classes) have some similarities, but each class has some of its own attributes and operations.
128. UMLClass Diagram Simplified methodology 1. Write down detailed description of problem 2. Identify all (relevant) nouns and verbs 3. From list of nouns, select objects 4. Identify data components of each object 5. From list of verbs, select operations
129. UMLClass Diagram A place to buy candy is from a candy machine. The candy machine has four dispensers to hold and release items sold by the candy machine as well as a cash register. The machine sells four products— candies, chips, gum, and cookies— each stored in a separate dispenser. The program should do the following: Showthe customer the different productssold by the candy machine Let the customermakethe selection Showthe customerthe cost of the item selected Acceptmoney from the customer Return change Release the item; that is, makethe sale textual analysis
130. UMLClass DiagramTextual Analysis Place, candy, candy machine, cafeteria, dispenser, items, cash register, chips, gum, cookies, customer, products, cost ( of the item), money, and change. In this description of the problem, products stand for items such as candy, chips, gum, and cookies. In fact, the actual product in the machine is not that important. What is important is to note that there are four dispensers, each capable of dispensing one product. Further, there is one cash register. Thus, the candy machine consists of four dispensers and one cash register. Graphically, this can be represented as in Figure 6-14.
132. UMLClass DiagramTextual Analysis You can see that the program you are about to write is supposed to deal with dispensers and cash registers. That is, the main objects are four dispensers and a cash register. Because all the dispensers are of the same type, you need to create a class, say, Dispenser, to create the dispensers. Similarly, you need to create a class, say, CashRegister, to create a cash register. We will create the classCandyMachine containing the four dispensers, a cash register, and the application program.
133. UMLClass DiagramTextual Analysis Dispenser To make the sale, at least one item must be in the dispenser and the customer must know the cost of the product. Therefore, the data members of a dispenser are: Product cost Number of items in the dispenser Cash Register The cash register accepts money and returns change. Therefore, the cash register has only one data member, which we call cashOnHand Candy Machine The classCandyMachine has four dispensers and a cash register. You can name the four dispensers by the items they store. Therefore, the candy machine has five data members— four dispensers and a cash register.
134. UMLClass Diagram Dispenser To make the sale, at least one item must be in the dispenser and the customer must know the cost of the product. Therefore, the data members of a dispenser are: Product cost Number of items in the dispenser
135. UMLClass Diagram Cash Register The cash register accepts money and returns change. Therefore, the cash register has only one data member, which we call cashOnHand
136. UMLClass Diagram Candy Machine The classCandyMachine has four dispensers and a cash register. You can name the four dispensers by the items they store. Therefore, the candy machine has five data members— four dispensers candy, chips, gum, cookies and a cash register.
137. UMLClass Diagram The relevant verbs are show ( selection), make ( selection), show ( cost), accept ( money), return ( change), and make ( sale). The verbs show ( selection) and make ( selection) relate to the candy machine. The verbs show ( cost) and make ( sale) relate to the dispenser. Similarly, the verbs accept ( money) and return ( change) relate to the cash register.
138. UMLClass Diagram The verbs show ( selection) and make ( selection) relate to the candy machine. Thus, the two possible operations are: showSelection: Show the number of products sold by the candy machine. makeSelection: Allow the customer to select the product.
139. UMLClass Diagram The verbs show ( cost) and make ( sale) relate to the dispenser. The verb show ( cost) applies to either printing or retrieving the value of the data member cost. The verb make ( sale) applies to reducing the number of items in the dispenser by 1. Of course, the dispenser has to be nonempty. You must also provide an operation to set the cost and the number of items in the dispenser. Thus, the operations for a dispenser object are: getCount: Retrieve the number of items in the dispenser. getProductCost: Retrieve the cost of the item. makeSale: Reduce the number of items in the dispenser by 1. setProductCost: Set the cost of the product. setNumberOfItems: Set the number of items in the dispenser
140. UMLClass Diagram Similarly, the verbs accept ( money) and return ( change) relate to the cash register. The verb accept ( money) applies to updating the money in the cash register by adding the money deposited by the customer. Similarly, the verb return ( change) applies to reducing the money in the cash register by returning the overpaid amount ( by the customer) to the customer. You also need to ( initially) set the money in the cash register and retrieve the money from the cash register. Thus, the possible operations on a cash register are: acceptAmount: Update the amount in the cash register. returnChange: Return the change. getCashOnHand: Retrieve the amount in the cash register. setCashOnHand: Set the amount in the cash register.
142. UMLClass Diagram Detailed Design Pseudocode for showSelectionmethod Show the selection to the customer Get selection If selection is valid and the dispenser corresponding to the selection is not empty, sell the product
143. UMLClass Diagram Detailed Design Pseudocode for makeSalemethod If the dispenser is nonempty: Prompt customer to enter the item cost Get the amount entered by the customer If the amount entered by the customer is less than the cost of the product Prompt customer to enter additional amount Calculate total amount entered by the customer If amount entered by the customer is at least the cost of the product Update the amount in the cash register Sell the product; that is, decrement the number of items in the dispenser by 1 Display an appropriate message If amount entered is less than cost of item Return the amount If the dispenser is empty Tell the customer that this product is sold out
144. UMLClass Diagram Detailed Design Pseudocode for main method Declare a variable of type cashRegister Declare and initialize four objects dispenserType For example: The statement dispenserType chips(100, 65); creates a dispenser object, chips, to hold chips; the number of items in the dispenser is 100 and the cost of an item is 65 cents
145. UMLClass Diagram Detailed Design Pseudocode for main method Declare additional variables as necessary Show menu Get the selection While not done (9 exits) Sell product (sellProduct) Show selection (showSelection) Get selection
146. Case Study: Candy Machine Implementation - JAVA CLASS Participation C!
151. OO Analysis & OO Design and Implement in JAVA Requirements A video store intends to offer rentals (and sales) of video tapes and disks to the public. The store management is determined to launch its operations with the support of a computer system. The management has already sourced a number of small-business software packages but has decided to develop its own system. The video store will keep a stock of video tapes, CDs and DVDs. The inventory has already been ordered from one supplier, but more suppliers will be approached in future orders. All video tapes and disks will be bar-coded so that a scanning machine integrated with the system can support the rentals and returns. The customer membership cards will also be bar-coded. Existing customers will be able to place reservations on videos to be collected at a specific date. The system must have a flexible search engine to answer customer enquiries, including enquiries about movies that the video store does not stock (but may order them on request). The central class is the Order. Associated with it are the Customer making the purchase and the Payment. A Payment is one of three kinds: Cash, Check, or Credit. The order contains OrderDetails (line items), each with its associated Item.
152. UMLUse Case Diagram – Textual Analysis Actor: Whoever or whatever (person, machine etc.) that interacts with a use case. Use case: It represents a complete unit of functionality of value to an actor. Use Case Diagram: It is a visual representation of actors and use cases together with any additional definitions and specifications. USE CASES Before a video can be rented out, the system confirms customer’s identity by swiping over scanner his/her Video Store membership card. Actors : ??? Use Case 1 : ???
153. UMLUse Case Diagram – Textual Analysis Actor: Whoever or whatever (person, machine etc.) that interacts with a use case. Use case: It represents a complete unit of functionality of value to an actor. Use Case Diagram: It is a visual representation of actors and use cases together with any additional definitions and specifications. USE CASES Before a video can be rented out, the system confirms customer’s identity by swiping over scanner his/her Video Store membership card. Actors : Customer and Employee Use Case 1 : Scan Membership Card
154. UMLUse Case Diagram – Textual Analysis Actor: Whoever or whatever (person, machine etc.) that interacts with a use case. Use case: It represents a complete unit of functionality of value to an actor. Use Case Diagram: It is a visual representation of actors and use cases together with any additional definitions and specifications. USE CASES Before a video can be rented out, the system confirms customer’s identity by swiping over scanner his/her Video Store membership card. Actors : Customer and Employee Use Case 1 : Scan Membership Card A video tape or disk can be swiped over scanner to obtain its description and price (fee) as part of customer’s enquiry or rental request. Actors : ??? Use Case 2 : ???
155. UMLUse Case Diagram – Textual Analysis Actor: Whoever or whatever (person, machine etc.) that interacts with a use case. Use case: It represents a complete unit of functionality of value to an actor. Use Case Diagram: It is a visual representation of actors and use cases together with any additional definitions and specifications. USE CASES Before a video can be rented out, the system confirms customer’s identity by swiping over scanner his/her Video Store membership card. Actors : Customer and Employee Use Case 1: Scan Membership Card A video tape or disk can be swiped over scanner to obtain its description and price (fee) as part of customer’s enquiry or rental request. Actors : Customer and Employee Use Case 2 : Scan Video Medium
156. UMLUse Case Diagram – Textual Analysis Actor: Whoever or whatever (person, machine etc.) that interacts with a use case. Use case: It represents a complete unit of functionality of value to an actor. Use Case Diagram: It is a visual representation of actors and use cases together with any additional definitions and specifications. USE CASES Before a video can be rented out, the system confirms customer’s identity by swiping over scanner his/her Video Store membership card. Actors : Customer and Employee Use Case 1 : Scan Membership Card A video tape or disk can be swiped over scanner to obtain its description and price (fee) as part of customer’s enquiry or rental request. Actors : Customer and Employee Use Case 2 : Scan Video Medium Customer pays the nominal fee before the video can be rented out. The payment may be with cash or debit/credit card. Actors : ??? Use Case 3 : ???
157. UMLUse Case Diagram – Textual Analysis Actor: Whoever or whatever (person, machine etc.) that interacts with a use case. Use case: It represents a complete unit of functionality of value to an actor. Use Case Diagram: It is a visual representation of actors and use cases together with any additional definitions and specifications. USE CASES Before a video can be rented out, the system confirms customer’s identity by swiping over scanner his/her Video Store membership card. Actors : Customer and Employee Use Case 1 : Scan Membership Card A video tape or disk can be swiped over scanner to obtain its description and price (fee) as part of customer’s enquiry or rental request. Actors : Customer and Employee Use Case 2 : Scan Video Medium Customer pays the nominal fee before the video can be rented out. The payment may be with cash or debit/credit card. Actors : Customer and Employee Use Case 3, 4 : Accept Payment and Charge Payment to Card
158. UMLUse Case Diagram – Textual Analysis USE CASES Before a video can be rented out, the system confirms customer’s identity by swiping over scanner his/her Video Store membership card. Actors : Customer and Employee Use Case 1 : Scan Membership Card A video tape or disk can be swiped over scanner to obtain its description and price (fee) as part of customer’s enquiry or rental request. Actors : Customer and Employee Use Case 2 : Scan Video Medium Customer pays the nominal fee before the video can be rented out. The payment may be with cash or debit/credit card. Actors : Customer and Employee Use Case 3, 4 : Accept Payment and Charge Payment to Card The system verifies all conditions for renting out the video, acknowledges that the transaction can go ahead, and can print the receipt for the customer. Actors : ??? Use Case 5 : ???
159. UMLUse Case Diagram – Textual Analysis USE CASES Before a video can be rented out, the system confirms customer’s identity by swiping over scanner his/her Video Store membership card. Actors : Customer and Employee Use Case 1 : Scan Membership Card A video tape or disk can be swiped over scanner to obtain its description and price (fee) as part of customer’s enquiry or rental request. Actors : Customer and Employee Use Case 2 : Scan Video Medium Customer pays the nominal fee before the video can be rented out. The payment may be with cash or debit/credit card. Actors : Customer and Employee Use Case 3, 4 : Accept Payment and Charge Payment to Card The system verifies all conditions for renting out the video, acknowledges that the transaction can go ahead, and can print the receipt for the customer. Actors : Customer and Employee Use Case 5 : Print Receipt
163. An Example: What is next? Use Case View Use Case Diagram Structural View Class Diagram Object Diagram Composite Structure Diagram Behavioral View Sequence Diagram Communication Diagram State Diagram Activity Diagram Interaction Overview Diagram Timing Diagram Implementation View Component Diagram Composite Structure Diagram Environment View Diagram
164. UML Activity Diagram – Textual Analysis Activity Diagram represents a behavior that is composed of individual elements. The behavior may be a specification of a use case. Activity Diagram can graphically represent the flow of events of a use case Shows the steps of computation We need to find actions (steps) in use case flows.
165. Finding actions in use case – Textual Analysis 1. The Employee requests the system to display the rental charge together with basic customer and video details. 2. If the Customer offers cash payment, the Employee handles the cash, confirms to the system that the payment has been received and asks the system to record the payment as made. 3. If the Customer offers debit/credit card payment, the Employee swipes the card and then requests the Customer to type the card’s PIN number, select debit or credit account, and transmit the payment. Once the payment has been confirmed electronically by the card provider, the system records the payment as made . Action 1: Display transaction details Action 2: Key in cash amount Action 3: Confirm transaction Action 4: Swipe the card Action 5: Accept card number Action 6: Select card account Action 3: Confirm transaction
166. Finding actions in use case – Textual Analysis 4. The Customer’s card does not swipe properly through the scanner. After three unsuccessful attempts, the Employee enters the card number manually. 5. The Customer does not have sufficient cash and does not offer card payment. The Employee asks the system to verify the Customer’s rating (which accounts for the Customer’s history of payments). Depending on the decision, the Employee cancels the transaction (and the use case terminates) or proceeds with partial payment (and the use case continues). Action 7: Enter card number manually Action 8: Verify Customer rating; Action 9: Refuse transaction; Action 10: Allow rent with no payment; Action 11: Allow rent with partial payment
167. UML Activity Diagram – Textual Analysis Activity diagram shows transitions between actions. Transitions can branch and merge Action 1: Display transaction details Action 4: Swipe the card Action 5: Accept card number Action 6: Select card account Action 3: Confirm transaction Action 2: Key in cash amount Action 3: Confirm transaction Action 7: Enter card number manually Action 8: Verify Customer rating; Action 9: Refuse transaction; Action 10: Allow rent with no payment; Action 11: Allow rent with partial payment
170. An Example: What is next? Use Case View Use Case Diagram Structural View Class Diagram Object Diagram Composite Structure Diagram Behavioral View Sequence Diagram Communication Diagram State Diagram Activity Diagram Interaction Overview Diagram Timing Diagram Implementation View Component Diagram Composite Structure Diagram Environment View Diagram
171. UML Class Diagram – Textual Analysis Class modeling captures the static view of the system although it also identifies operations that act on data. Class modeling elements Classes themselves Attributes (data)and operations (methods) of classes Relationships - associations, aggregation and composition, and generalization. Class diagram is a combined visual representation for class modeling elements. Assignment of use cases to classes FINDING CLASSES is an iterative task as the initial list of candidate classes is likely to change. Answering a few questions may help to determine whether a CONCEPT in a USE CASEis a candidate CLASS or not. The questions are following: Is the concept a container for data? Does it have separate attributes that will take on different values? Would it have many instance objects?
172. UML Class Diagram – Textual Analysis Before a video can be rented out, the system confirms customer’s identity by swiping over scanner his/her Video Store membership card. Classes?
173. UML Class Diagram – Textual Analysis Before a video can be rented out, the system confirms customer’s identity by swiping over scanner his/her Video Store membership card. Classes? Video, Customer, MembershipCard
174. UML Class Diagram – Textual Analysis Before a video can be rented out, the system confirms customer’s identity by swiping over scanner his/her Video Store membership card. Classes? Classes? Video, Customer, MembershipCard A video tape or disk can be swiped over scanner to obtain its description and price (fee) as part of customer’s enquiry or rental request.
175. UML Class Diagram – Textual Analysis Before a video can be rented out, the system confirms customer’s identity by swiping over scanner his/her Video Store membership card. Classes? Classes? Video, Customer, MembershipCard A video tape or disk can be swiped over scanner to obtain its description and price (fee) as part of customer’s enquiry or rental request. VideoTape VideoDisk, Customer, Rental
176. UML Class Diagram – Textual Analysis Before a video can be rented out, the system confirms customer’s identity by swiping over scanner his/her Video Store membership card. Classes? Classes? Classes? Video, Customer, MembershipCard A video tape or disk can be swiped over scanner to obtain its description and price (fee) as part of customer’s enquiry or rental request. VideoTape VideoDisk, Customer, Rental Customer pays the nominal fee before the video can be rented out. The payment may be with cash or debit/credit card.
177. UML Class Diagram – Textual Analysis Classes? Classes? Classes? Before a video can be rented out, the system confirms customer’s identity by swiping over scanner his/her Video Store membership card. Video, Customer, MembershipCard A video tape or disk can be swiped over scanner to obtain its description and price (fee) as part of customer’s enquiry or rental request. VideoTape VideoDisk, Customer, Rental Customer pays the nominal fee before the video can be rented out. The payment may be with cash or debit/credit card. Customer, Video, Rental, Payment
178. UML Class Diagram – Textual Analysis Classes? Classes? Classes? Classes? Before a video can be rented out, the system confirms customer’s identity by swiping over scanner his/her Video Store membership card. Video, Customer, MembershipCard A video tape or disk can be swiped over scanner to obtain its description and price (fee) as part of customer’s enquiry or rental request. VideoTape VideoDisk, Customer, Rental Customer pays the nominal fee before the video can be rented out. The payment may be with cash or debit/credit card. Customer, Video, Rental, Payment The system verifies all conditions for renting out the video, acknowledges that the transaction can go ahead, and can print the receipt for the customer.
182. UML Class Diagram– Attributes– Textual Analysis Identifying attributesfor each class Attributes are discovered form user requirements and domain knowledge. One or more attributes in a class will have unique values across all the instances (objects) of the class. Such attributes are called keys.