SlideShare a Scribd company logo
COSC 1320Please 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/webctpsid/ mmddyya!
Introduction to Computer Science IICOSC 1320/6305Lecture 1: Software Engineering and Classes       UML, OOA/OOD/JAVA Implementation A TOP DOWN EXAMPLE (Chapter 12)
Copyright © 2011 Dept of Computer Science - University of Houston. All rights reserved.7-3
Class Participation NetBeans Projects
Software EngineeringSoftware Engineering is the study of the techniques and theory that support the development of high-quality softwareThe focus is on controlling the development process to achieve consistently good resultsWe want to:satisfy the client – the person or organization who sponsors the developmentmeet the needs of the user – the people using the software for its intended purpose
Goals of Software EngineeringSolve the right problemmore difficult than it might seemclient interaction is keyDeliver a solution on time and under budgetthere are always trade-offsDeliver a high-quality solutionbeauty is in the eye of the beholderwe must consider the needs of various stakeholders
Aspects of software quality
Development ModelsA development life cycle defines a process to be followed during product developmentMany software development models have been introducedAll of them address the following fundamental issues in one way or another:problem analysis (What?)design (How?)implementationevaluationmaintenance
Problem Analysis - WhatWe must specify the requirements of the software system
Problem Analysis - WhatWe must specify the requirements of the software systemMust be based on accurate informationVarious techniques:discussions and negotiations with the clientmodeling the problem structure and data flowobservation of client activitiesanalysis of existing solutions and systems
Design - HowWe must specify the solutionYou would not consider building a bridge without a designDesign involves determining:the overall software structure (architecture)the key objects, classes, and their relationshipsAlternatives should be considered
ImplementationWe must turn the design into functional softwareToo many people consider this the primary act of software developmentMay involve the reuse of existing software components
EvaluationWe must verify that the system conforms to the requirementsThis includes, but goes way beyond, testing code with test casesIt is possible to build a system that has no bugs and yet is completely wrong
MaintenanceAfter a system is initially developed, it must be maintainedThis includes:fixing errorsmaking enhancements to meet the changing needs of usersThe better the development effort, the easier the maintenance tasks will be
The Waterfall ModelOne of the earliest development modelsEach stage flows into the nextDriven by documentationAdvantages:Lays out clear milestones and deliverablesHas high visibility – managers and clients can see the statusDisadvantages:late evaluationnot realistic in many situations
The Spiral ModelDeveloped by Barry Boehm in the mid '80sEmbraces an iterative process, where activities are performed over and over again for different aspects of the systemDesigned to reduce the risks involvedContinually refines the requirementsEach loop through the spiral is a complete phase of development
The Evolutionary Model***Like the spiral model, an evolutionary approach embraces continual refinementIntermediate versions of the system are created for evaluation by both the developers and the clientMay be more difficult to maintain depending on the attention given to the iterations
The Unified Modeling LanguageThe Unified Modeling Language (UML) has become a standard notation for software analysis  (OOA) & design (OOD)It is language independentIt includes various types of diagrams (models) which use specific icons and notationsHowever, it is flexible – the details you include in a given diagram depend on what you are trying to capture and communicate
UML Class DiagramsUML class diagrams may include:The classes used in the systemThe static relationships among classesThe attributesand operations of each classThe constraints on the connections among objectsAn attributeis class level data, including variables and constantsAn operation is essentially equivalent to a methodMay include visibility details+   public    private#   protected
UML class diagram showing inheritance relationships
UML class diagram showing an association
One class shown as an aggregate of other classes
UML diagram showing a class implementing an interface
One class indicating its use of another
ObjectivesAdvise on the classSoftware EngineeringProblem solvingMemoryClasses
Life Cycle“Read a sequence of marks from the user, ending with the word ‘done’ and then print the average of the marks.”
Specify — Design — Code — Test              Edit—Compile—Run  cycle: Problem SolvingInitialDesignEdit:typing in the Java code SpecificationCompile:Translating to executable instructions Run:Testing the program to see that it works
Life CycleProblem⇒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.”
Life CycleProblem⇒ 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
Life Cycle⇒ Problem description⇒ Design of Solution ⇒Computer program⇒ Test and debugimport 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\n",   sum/count);}}
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:  70Enter next mark:  85Enter next mark:  65Enter next mark:  doneaverage mark = 73.33Enter next mark:  doneError: divide by zero
ObjectivesAdvise on the classSoftware EngineeringProblem solvingMemoryClasses
Machine Languages, Assembly Languages, and High-level LanguagesThree types of programming languagesMachine languagesStrings of numbers giving machine specific instructionsExample:+1300042774+1400593419+1200274027Assembly languagesEnglish-like abbreviations representing elementary computer operations (translated via assemblers)Example:LOAD   BASEPAYADD    OVERPAYSTORE  GROSSPAYHigh-level languagesCodes similar to everyday EnglishUse mathematical notations (translated via compilers)Example:grossPay = basePay + overTimePay
History of CCEvolved by Ritchie from two previous programming languages, BCPL and BUsed to develop UNIXUsed to write modern operating systemsHardware independent (portable)By late 1970's C had evolved to "Traditional C“StandardizationMany slight variations of C existed, and were incompatibleCommittee formed to create a "unambiguous, machine-independent" definitionStandard created in 1989, updated in 1999
The C Standard LibraryC programs consist of pieces/modules called functionsA programmer can create his own functionsAdvantage: the programmer knows exactly how it worksDisadvantage: time consumingProgrammers will often use the C library functionsUse these as building blocksAvoid re-inventing the wheel!If a premade function exists, generally best to use it rather than rewrite Library functions carefully written, efficient, and portable
The Key Software Trend: Object TechnologyObjects Reusable software componentsthat model items in the real worldMeaningful software unitsDate 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 programmingFavor modularity
C++C++Superset of C developed by BjarneStroustrup at Bell Labs"Spruces up" C, and provides object-oriented capabilitiesObject-oriented very powerful10 to 100 fold increase in productivityDominant language in industry and academia
JavaJava is used to Create Web pages with dynamic and interactive content Develop large-scale enterprise applicationsEnhance the functionality of Web serversProvide applications for consumer devices (such as cell phones, pagers and personal digital assistants)
Other High-level LanguagesOther high-level languagesFORTRANUsed for scientific and engineering applicationsCOBOLUsed to manipulate large amounts of dataPascal  Intended for academic use
Basics of a Typical C Program Development EnvironmentPreprocessor programprocesses the code.Compiler creates object code and storesit on disk.CompilerLinker links the objectcode with the librariesPrimary MemoryLoaderLoader puts program in memory.Primary MemoryCPU takes eachinstruction and executes it, possibly storing new data values as the program executes. CPUPreprocessorLinkerEditorDiskDiskDiskDiskDisk...... ......Phases of C++ Programs:EditPreprocessCompileLinkLoadExecuteProgram is created inthe editor and storedon disk.
Memory ConceptsVariable namesCorrespond to actual locations in computer's memoryEvery variable has name, type, size and valueWhen new value placed into variable, overwrites previous valueReading variables from memory nondestructive
Memory Concepts4545724572integer1integer1integer2integer1integer2117sumstd::cin >> integer1;Assume user entered 45std::cin >> integer2;Assume user entered 72sum = integer1 + integer2;
Memory927892799280928192829283928492859286Main memory is divided into many memory locations (or cells)Each memory cell has a numeric address, which uniquely identifies it
Storing InformationEach memory cell stores a set number of bits (usually 8 bits, or one byte)Large values arestored in consecutivememory locations92789279928092819282928392849285928610011010
References38num1"Steve Jobs"name1Note that a primitive variable contains the value itself, but an object variable contains the address of the objectAn object reference can be thought of as a pointer to the location of the objectRather than dealing with arbitrary addresses, we often depict a reference graphically
Assignment Revisited38num1Before:96num238num1After:38num2The act of assignment  =takes a copy of a value and stores it in a variableFor primitive types:num2 = num1;
Reference Assignment"Steve Jobs"name1Before:"Steve Wozniak"name2"Steve Jobs"name1After:name2For object references, assignment copies the address:name2 = name1;
Numeric Primitive DataTypebyteshortintlongfloatdoubleStorage8 bits16 bits32 bits64 bits32 bits64 bitsMin Value-128-32,768-2,147,483,648< -9 x 1018+/- 3.4 x 1038+/- 1.7 x 10308Max Value12732,7672,147,483,647> 9 x 1018The difference between the various numeric primitive types is their size, and therefore the values they can store:927892799280928192829283928492859286
C/C++ Program12345678
Another Picture
Assembly & Machine Language
An Assembler
Compiler
Software: User ProgramsPrograms that are neither OS programs nor applications are called user programs.User programs are what you’ll be writing in this course.
Putting it all togetherDiskRAMCPUCacheOSAppBusPrograms and applications that are not running are stored on disk.
Putting it all togetherDiskRAMCPUCacheOSAppAppOSBus    When you launch a program, the OS controls the CPU and loads the program from disk to RAM.
Putting it all togetherDiskRAMCPUCacheOSAppAppAppBusThe OS then relinquishes the CPU to the program, which begins to run.
The Fetch-Execute CycleAs the program runs, it repeatedly  fetches the next instruction (from memory/cache), executes it, and stores any results back to memory.DiskRAMCPUCacheOSAppAppAppBusThat’s all a computer does: fetch-execute-store, millions of times each second!
Object Oriented Paradigm
OverviewUnderstand Classesand Objects.Understand some of the key concepts/features in the Object Oriented paradigm.Benefits of Object Oriented paradigm.
OOP: Model, map, Reuse, extendModel the real world problem to user’s perceiveUse similar metaphor in computational env.Construct Reusable componentsCreate new components from existing ones.
Examples of Objects
Classes :Objectswith the same attributes and behavior
Object Oriented Paradigm: FeaturesEncapsulationData AbstractionSingle InheritanceOOP ParadigmPolymorphismPersistenceDelegationGenericityMultiple Inheritance
Java’s OO FeaturesEncapsulationData AbstractionSingle InheritanceJavaOOP ParadigmPolymorphismPersistenceDelegationGenericityMultiple Inheritance
EncapsulationAssociates the Code & the Datait manipulates into a single unit; and keeps them safe from external interference and misuse.EncapsulationData AbstractionSingle InheritanceOOP ParadigmPolymorphismPersistenceDelegationDataGenericityCodeMultiple Inheritance
Data AbstractionThe 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).EncapsulationData AbstractionSingle InheritanceOOP ParadigmPolymorphismPersistenceDelegationGenericityMultiple Inheritance
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.
ClassDefinition Syntax69
Class - Exampleclass Account { private StringaccountName;privatedoubleaccountBalance;publicwithdraw();publicdeposit();public determineBalance();} // Class Account
ClassClass is a set of attributesand operations that are performed on the attributes.StudentCircleAccountaccountNameaccountBalancenameagestudentIdcentreradiuswithdraw()deposit()determineBalance()area()circumference()getName()getId()
ObjectsAn Object Oriented system is a collection of interacting Objects.Objectis an instance of a class.
Classes /ObjectsJohn and Jill are objects of classStudent:JohnStudent:Jill:circleAcircleA and circleB are objects of classCircleCircle:circleB
ClassA 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.
ObjectObjects have state and classes don’t.Johnis an object (instance) of class Student. name = “John”, age  = 20,  studentId = 1236Jill is an object (instance) of class Student. name = “Jill”, age  = 22, studentId = 2345circleAis an object (instance) of class Circle. centre = (20,10), radius  = 25circleB is an object (instance) of class Circle. centre = (0,0),  radius  = 10
EncapsulationAll 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.
Encapsulation - ExamplemessagewithdrawdepositaccountBalancemessagedetermine Balancemessageclass Account { privatedoubleaccountBalance;public withdraw();public deposit();public determineBalance();} // Class Account
Data AbstractionThe 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.
Abstraction - Exampleclass Account { 	private String accountName;	private double accountBalance;    public  withdraw();	public  deposit();	public  determineBalance();} // Class Account Creates a data type AccountAccountacctX;
InheritanceParentChildNew 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
Inheritance  - ExampleExamplesDefine Person to be a classA Person has attributes, such as age, height, genderAssign values to attributes when describing objectDefine 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 PersonDefine lecturer to be a subclass of Personlecturer has all attributes of Person, plus attributes of his/her own (staff_id, subjectID1, subjectID2)
Inheritance - ExampleCircle Class can bea subclass (inheritedfrom) of a parent class - ShapeShapeCircleRectangle
Inheritance - ExampleInheritance can also have multiple levels.ShapeCircleRectangleGraphicCircle
Uses of Inheritance - ReuseIf 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.
Uses of Inheritance - ReuseCirclecentreradiusarea()circumference()move(newCentre)move(newCentre){centre = newCentre;}Rectanglecentreheightwidtharea()circumference()move(newCentre)move(newCentre){   centre = newCentre;}move(newCentre){centre = newCentre;}
86Uses of Inheritance - ReuseShapecentremove(newCentre){centre = newCentre}area()circumference()move(newCentre)RectangleCircleheightwidthradiusarea()circumference()area()circumference()
Uses of Inheritance - SpecializationSpecialized 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().
88Circlecentreradiusarea()circumference()move(newCentre)area(){   return pi*r^2;}Uses of Inheritance - SpecializationRectanglecentreheightwidtharea()circumference()move(newCentre)area(){    return height*width;}
89Uses of Inheritance - Specializationarea(){   return pi*r^2;}Shapecentrearea();  - not implemented and left for the child classesto implementarea()circumference()move(newCentre)RectangleCircleheightwidthradiusarea()circumference()area(){    return height*width;}area()circumference()
Uses of Inheritance – Common InterfaceAll 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().
Uses of Inheritance - ExtensionExtend 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()
Uses of Inheritance - ExtensionShapecentrearea()circumference()move(newCentre)RectangleCircleheightwidthradiusarea()circumference()rotate90degrees()area()circumference()
Uses of Inheritance – Multiple InheritanceInherit properties from more than one class. This is called Multiple Inheritance.ShapeGraphicsCircle
Uses of Multiple InheritanceThis 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++.
Uses of Inheritance – Multiple InheritanceShapecentrearea()circumference()move(newCentre)Circleradiusarea()circumference()GraphicCirclecolorpaint()
PolymorphismPolymorphic which means “many forms” has Greek roots.Poly – manyMorphos  - 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.
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 beexecutedrectangleA = new Rectangle(); Create a new rectangle objectshape= rectangleA;shape.area()area() method for rectangle will be executed.
Polymorphism – Method OverloadingMultiple 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.
99Polymorphism – Operator OverloadingAllows regular operators such as +, -, *, / to have different meanings based on the type.e.g. + operator for Circle can re-definedCircle c = c + 2;Not supported in JAVA. C++ supports it.
100PersistenceThe 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.
101Why OOP? Greater ReliabilityBreak complex software projects into small, self-contained, and modular objectsMaintainabilityModular objects make locating bugs easier, with less impact on the overall projectGreater Productivity through Reuse!Faster Design and Modelling
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.
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.
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.
SummaryObject Oriented Analysis, Design, and Programming is a Powerful paradigmEnables Easy Mapping of Real world Objects to Objects in the ProgramThis is enabled by OO features:EncapsulationData AbstractionInheritancePolymorphismPersistenceStandard OO Analysis and Design (UML) and Programming Languages (C++/Java) are readily accessible.
What We Will Learn?How to solve a problem.Using JavaJava is a good language to start doing object oriented (OO) in because it attempts to stay true to all the different OO paradigms.Copyright © 2011 Dept of Computer Science - University of Houston. All rights reserved.
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.OOPPPVariablesDataFunctionsMethodsClass
Example programDesign and Implement a program to calculate perimeter of a circle.PPCOOPJavaCopyright © 2011 Dept of Computer Science - University of Houston. All rights reserved.7-108CLASS Participation A!
Example program, PP in CDesign and ImplementPPVariablesFunctionsDriver.c#include <iostream>const double PI=3.14;void main(){doublecircleRadius = 10;double circlePerimeter = 2*PI*circleRadius;printf("Circle Perimiter%f\n",circlePerimeter);system("pause");}CLASS Participation B!
Copyright © 2011 Dept of Computer Science - University of Houston. All rights reserved.7-110CLASS Participation B!
Example program, OOP in Java7-111The core of OOP: “Put related things together.”Design Implement  Circle.javapublic 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.javapublic classMain {public static void main(String[] args)   {        Circle circle = new Circle(10);System.out.println("Circle Perimeter " + circle.getPerimeter());}}DataOOPMethods
Copyright © 2011 Dept of Computer Science - University of Houston. All rights reserved.7-112
Example program, PP in CDesign and ImplementPPVariablesFunctionsDriver.c#include <iostream>const double PI=3.14;void main(){doublecircleRadius = 10;double circlePerimeter = 2*PI*circleRadius;printf("Circle Perimiter%f\n",circlePerimeter);system("pause");}CLASS Participation B!
Copyright © 2011 Dept of Computer Science - University of Houston. All rights reserved.7-114CLASS Participation B!
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”
OOAnalysis & Design: UMLUnified 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.
Unified Modeling LanguageUMLprovides 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.
1. UML Use Case DiagramsThe 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.
1. UML Use Case DiagramsWe 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 system1. 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
1. Use Case DiagramsDrawing Use Case Diagrams1. 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 ItemUse Case 1Use Case 2Use Case 3Use Case 4
2. UMLClass DiagramsThe 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.
2. UML Class DiagramsNotice 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...
2. UML Class DiagramsClass 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.javaIn UMLrelationships are presumed to be bidirectional unless the arrowhead is present to restrict them.
2. UML Class DiagramsComposition 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.
2. UML Class DiagramsThe 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.
2. UML Class DiagramsAnother 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.
Candy Machine Case StudyRequirementsTextual AnalysisUML Modeling
UMLClass DiagramSimplified methodology1. Write down detailed description of problem2. Identify all (relevant) nouns and verbs3. From list of nouns, select objects4. Identify data components of each object5. From list of verbs, select operations
UMLClass DiagramA 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 machineLet the customermakethe selectionShowthe customerthe cost of the item selectedAcceptmoney from the customerReturn changeRelease the item; that is, makethe saletextual analysis
UMLClass DiagramTextual AnalysisPlace, 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.
UMLClass Diagram
UMLClass DiagramTextual AnalysisYou 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.
UMLClass DiagramTextual AnalysisDispenser 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  cashOnHandCandy 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.
UMLClass DiagramDispenser 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
UMLClass DiagramCash Register The cash register accepts money and returns change. Therefore, the cash register has only one data member, which we call  cashOnHand
UMLClass DiagramCandy 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.
UMLClass DiagramThe 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.
UMLClass DiagramThe 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.
UMLClass DiagramThe 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
UMLClass DiagramSimilarly, 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.
UMLClass Diagram
UMLClass DiagramDetailed Design Pseudocode for showSelectionmethodShow the selection to the customerGet selectionIf selection is valid and the dispenser corresponding to the selection is not empty, sell the product
UMLClass DiagramDetailed Design Pseudocode for makeSalemethodIf the dispenser is nonempty:Prompt customer to enter the item costGet the amount entered by the customerIf the amount entered by the customer is less than the cost of the productPrompt customer to enter additional amountCalculate total amount entered by the customerIf amount entered by the customer is at least the cost of the productUpdate the amount in the cash registerSell the product; that is, decrement the number of items in the dispenser by 1Display an appropriate messageIf amount entered is less than cost of itemReturn the amountIf the dispenser is emptyTell the customer that this product is sold out
UMLClass DiagramDetailed Design Pseudocode for main methodDeclare a variable of type cashRegisterDeclare and initialize four objects dispenserTypeFor 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
UMLClass DiagramDetailed Design Pseudocode for main methodDeclare additional variables as necessaryShow menuGet the selectionWhile not done (9 exits)Sell product (sellProduct)Show selection (showSelection)Get selection
Case Study: Candy Machine Implementation - JAVACLASS Participation C!
Case Study: Candy Machine Implementation- JAVA
Case Study: Candy Machine Implementation- JAVA
JAVA
Video Store Case StudyRequirementsTextual AnalysisUML ModelingCopyright © 2011 Dept of Computer Science - University of Houston. All rights reserved.7-150
OO Analysis & OO Design and Implement in JAVARequirementsA 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.
UMLUse Case Diagram – Textual AnalysisActor: 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 CASESBefore 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	: ???
UMLUse Case Diagram – Textual AnalysisActor: 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 CASESBefore 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 EmployeeUse Case 1	: Scan Membership Card
UMLUse Case Diagram – Textual AnalysisActor: 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 CASESBefore 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 EmployeeUse Case 1	: Scan Membership CardA 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	: ???
UMLUse Case Diagram – Textual AnalysisActor: 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 CASESBefore 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 EmployeeUse Case 1: Scan Membership CardA 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 EmployeeUse Case 2	: Scan Video Medium
UMLUse Case Diagram – Textual AnalysisActor: 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 CASESBefore 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 EmployeeUse Case 1	: Scan Membership CardA 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 EmployeeUse Case 2	: Scan Video MediumCustomer 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	: ???
UMLUse Case Diagram – Textual AnalysisActor: 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 CASESBefore 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 EmployeeUse Case 1	: Scan Membership CardA 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 EmployeeUse Case 2	: Scan Video MediumCustomer pays the nominal fee before the video can be rented out. The payment may be with cash or debit/credit card. Actors	: Customer and EmployeeUse Case 3, 4	: Accept  Payment and Charge Payment to Card
UMLUse Case Diagram – Textual AnalysisUSE CASESBefore 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 EmployeeUse Case 1	: Scan Membership CardA 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 EmployeeUse Case 2	: Scan Video MediumCustomer pays the nominal fee before the video can be rented out. The payment may be with cash or debit/credit card. Actors	: Customer and EmployeeUse Case 3, 4	: Accept  Payment and Charge Payment to CardThe 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	: ???
UMLUse Case Diagram – Textual AnalysisUSE CASESBefore 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 EmployeeUse Case 1	: Scan Membership CardA 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 EmployeeUse Case 2	: Scan Video MediumCustomer pays the nominal fee before the video can be rented out. The payment may be with cash or debit/credit card. Actors	: Customer and EmployeeUse Case 3, 4	: Accept  Payment and Charge Payment to CardThe 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 EmployeeUse Case 5	: Print Receipt
An Example: UML Use Case Diagram
Lecture 1 uml with java implementation
UC3: Accept Payment
An Example: What is next?Use Case ViewUse Case DiagramStructural ViewClass DiagramObject DiagramComposite Structure DiagramBehavioral ViewSequence DiagramCommunication DiagramState DiagramActivity DiagramInteraction Overview DiagramTiming DiagramImplementation ViewComponent DiagramComposite Structure DiagramEnvironment ViewDiagram
UML Activity Diagram – Textual AnalysisActivity 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 caseShows the steps of computationWe need to find actions (steps) in use case flows.
Finding actions in use case – Textual Analysis1. 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 detailsAction 2:  Key in cash amountAction 3:  Confirm transactionAction 4:  Swipe the cardAction 5:  Accept card numberAction 6:  Select card accountAction 3:  Confirm transaction
Finding actions in use case – Textual Analysis4. 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 manuallyAction 8:    Verify Customer rating;Action 9:    Refuse transaction;Action 10:  Allow rent with no payment;Action 11:  Allow rent with partial payment
UML Activity Diagram – Textual AnalysisActivity diagram shows transitions between actions.Transitions can branch and mergeAction 1: Display transaction detailsAction 4:  Swipe the cardAction 5:  Accept card numberAction 6:  Select card accountAction 3:  Confirm transactionAction 2:  Key in cash amountAction 3:  Confirm transactionAction 7: Enter card number manuallyAction 8: Verify Customer rating;Action 9:  Refuse transaction;Action 10:  Allow rent with no payment;Action 11:  Allow rent with partial payment
UML Activity DiagramA5:A1:A4:A6:A2:A7:A8:A11:A10:A3:A9:
An Example: Activity Diagram
An Example: What is next?Use Case ViewUse Case DiagramStructural ViewClass DiagramObject DiagramComposite Structure DiagramBehavioral ViewSequence DiagramCommunication DiagramState DiagramActivity DiagramInteraction Overview DiagramTiming DiagramImplementation ViewComponent DiagramComposite Structure DiagramEnvironment ViewDiagram
UML Class Diagram – Textual AnalysisClass modeling captures the static view of the system although it also identifies operations that act on data. Class modeling elementsClasses themselvesAttributes (data)and operations (methods) of classesRelationships - associations, aggregation and composition, and generalization.Class diagram is a combined visual representation for class modeling elements.Assignment of use cases to classesFINDING 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?
UML Class Diagram – Textual AnalysisBefore a video can be rented out, the system confirms customer’s identity by swiping over scanner his/her Video Store membership card.Classes?
UML Class Diagram – Textual AnalysisBefore 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
UML Class Diagram – Textual AnalysisBefore 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,MembershipCardA 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.
UML Class Diagram – Textual AnalysisBefore 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,MembershipCardA 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.VideoTapeVideoDisk,Customer,Rental
UML Class Diagram – Textual AnalysisBefore 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,MembershipCardA 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.VideoTapeVideoDisk,Customer,RentalCustomer pays the nominal fee before the video can be rented out. The payment may be with cash or debit/credit card.
UML Class Diagram – Textual AnalysisClasses?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,MembershipCardA 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.VideoTapeVideoDisk,Customer,RentalCustomer 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
UML Class Diagram – Textual AnalysisClasses?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,MembershipCardA 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.VideoTapeVideoDisk,Customer,RentalCustomer pays the nominal fee before the video can be rented out. The payment may be with cash or debit/credit card. Customer,Video,Rental,PaymentThe system verifies all conditions for renting out the video, acknowledges that the transaction can go ahead, and can print the receipt for the customer.
UML Class Diagram – Textual AnalysisClasses?Classes?Classes?Classes?Video,Customer,MembershipCardVideoTapeVideoDisk,Customer,RentalCustomer,Video,Rental,PaymentRental,Receipt
UML Class Diagram – Textual Analysis
UML Class Diagram
UML Class Diagram– Attributes– Textual AnalysisIdentifying attributesfor each classAttributes 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.
C2C3
Lecture 1 uml with java implementation
UML Class Diagram
Referenceshttp://edn.embarcadero.com/article/31863http://atlas.kennesaw.edu/~dbraun/csis4650/A&D/UML_tutorial/http://www.objectmentor.com/resources/articles/umlClassDiagrams.pdfhttp://www.objectmentor.com/resources/publishedArticles.htmlhttp://www.objectmentor.com/resources/articles/usecases.pdfhttp://www.objectmentor.com/resources/articles/Use_Cases_UFJP.pdfhttp://www.tutorialspoint.com/uml/uml_overview.htm

More Related Content

What's hot (20)

Object oriented architecture in erp
Object  oriented architecture in erpObject  oriented architecture in erp
Object oriented architecture in erp
Preyanshu Saini
 
Abstract class and Interface
Abstract class and InterfaceAbstract class and Interface
Abstract class and Interface
Haris Bin Zahid
 
Class Diagram | OOP and Design Patterns by Oum Saokosal
Class Diagram | OOP and Design Patterns by Oum SaokosalClass Diagram | OOP and Design Patterns by Oum Saokosal
Class Diagram | OOP and Design Patterns by Oum Saokosal
OUM SAOKOSAL
 
C#, OOP introduction and examples
C#, OOP introduction and examplesC#, OOP introduction and examples
C#, OOP introduction and examples
agni_agbc
 
SKILLWISE - OOPS CONCEPT
SKILLWISE - OOPS CONCEPTSKILLWISE - OOPS CONCEPT
SKILLWISE - OOPS CONCEPT
Skillwise Group
 
Introduction to oop
Introduction to oopIntroduction to oop
Introduction to oop
colleges
 
Introduction to oop
Introduction to oop Introduction to oop
Introduction to oop
Kumar
 
Java interfaces
Java interfacesJava interfaces
Java interfaces
jehan1987
 
Abstraction in java [abstract classes and Interfaces
Abstraction in java [abstract classes and InterfacesAbstraction in java [abstract classes and Interfaces
Abstraction in java [abstract classes and Interfaces
Ahmed Nobi
 
Abstract class in java
Abstract class in javaAbstract class in java
Abstract class in java
Lovely Professional University
 
What are Abstract Classes in Java | Edureka
What are Abstract Classes in Java | EdurekaWhat are Abstract Classes in Java | Edureka
What are Abstract Classes in Java | Edureka
Edureka!
 
Interface in java
Interface in javaInterface in java
Interface in java
Lovely Professional University
 
OOP Unit 2 - Classes and Object
OOP Unit 2 - Classes and ObjectOOP Unit 2 - Classes and Object
OOP Unit 2 - Classes and Object
dkpawar
 
C# Summer course - Lecture 2
C# Summer course - Lecture 2C# Summer course - Lecture 2
C# Summer course - Lecture 2
mohamedsamyali
 
General OOP Concepts
General OOP ConceptsGeneral OOP Concepts
General OOP Concepts
Praveen M Jigajinni
 
Unit 1 OOSE
Unit 1 OOSE Unit 1 OOSE
Unit 1 OOSE
ChhayaShelake
 
Introduction to oops concepts
Introduction to oops conceptsIntroduction to oops concepts
Introduction to oops concepts
Nilesh Dalvi
 
Oops And C++ Fundamentals
Oops And C++ FundamentalsOops And C++ Fundamentals
Oops And C++ Fundamentals
Subhasis Nayak
 
Interface in java ,multiple inheritance in java, interface implementation
Interface in java ,multiple inheritance in java, interface implementationInterface in java ,multiple inheritance in java, interface implementation
Interface in java ,multiple inheritance in java, interface implementation
HoneyChintal
 
Slide 5 Class Diagram
Slide 5 Class DiagramSlide 5 Class Diagram
Slide 5 Class Diagram
Niloy Rocker
 
Object oriented architecture in erp
Object  oriented architecture in erpObject  oriented architecture in erp
Object oriented architecture in erp
Preyanshu Saini
 
Abstract class and Interface
Abstract class and InterfaceAbstract class and Interface
Abstract class and Interface
Haris Bin Zahid
 
Class Diagram | OOP and Design Patterns by Oum Saokosal
Class Diagram | OOP and Design Patterns by Oum SaokosalClass Diagram | OOP and Design Patterns by Oum Saokosal
Class Diagram | OOP and Design Patterns by Oum Saokosal
OUM SAOKOSAL
 
C#, OOP introduction and examples
C#, OOP introduction and examplesC#, OOP introduction and examples
C#, OOP introduction and examples
agni_agbc
 
SKILLWISE - OOPS CONCEPT
SKILLWISE - OOPS CONCEPTSKILLWISE - OOPS CONCEPT
SKILLWISE - OOPS CONCEPT
Skillwise Group
 
Introduction to oop
Introduction to oopIntroduction to oop
Introduction to oop
colleges
 
Introduction to oop
Introduction to oop Introduction to oop
Introduction to oop
Kumar
 
Java interfaces
Java interfacesJava interfaces
Java interfaces
jehan1987
 
Abstraction in java [abstract classes and Interfaces
Abstraction in java [abstract classes and InterfacesAbstraction in java [abstract classes and Interfaces
Abstraction in java [abstract classes and Interfaces
Ahmed Nobi
 
What are Abstract Classes in Java | Edureka
What are Abstract Classes in Java | EdurekaWhat are Abstract Classes in Java | Edureka
What are Abstract Classes in Java | Edureka
Edureka!
 
OOP Unit 2 - Classes and Object
OOP Unit 2 - Classes and ObjectOOP Unit 2 - Classes and Object
OOP Unit 2 - Classes and Object
dkpawar
 
C# Summer course - Lecture 2
C# Summer course - Lecture 2C# Summer course - Lecture 2
C# Summer course - Lecture 2
mohamedsamyali
 
Introduction to oops concepts
Introduction to oops conceptsIntroduction to oops concepts
Introduction to oops concepts
Nilesh Dalvi
 
Oops And C++ Fundamentals
Oops And C++ FundamentalsOops And C++ Fundamentals
Oops And C++ Fundamentals
Subhasis Nayak
 
Interface in java ,multiple inheritance in java, interface implementation
Interface in java ,multiple inheritance in java, interface implementationInterface in java ,multiple inheritance in java, interface implementation
Interface in java ,multiple inheritance in java, interface implementation
HoneyChintal
 
Slide 5 Class Diagram
Slide 5 Class DiagramSlide 5 Class Diagram
Slide 5 Class Diagram
Niloy Rocker
 

Similar to Lecture 1 uml with java implementation (20)

Cnpm bkdn
Cnpm bkdnCnpm bkdn
Cnpm bkdn
Ankit yadav
 
Chapter 10
Chapter 10 Chapter 10
Chapter 10
University of Calgary, School of Creative and Performing Arts
 
10tait
10tait10tait
10tait
University of Calgary, School of Creative and Performing Arts
 
Software engineering
Software engineeringSoftware engineering
Software engineering
Fahe Em
 
Software engineering
Software engineeringSoftware engineering
Software engineering
Fahe Em
 
Beekman5 std ppt_13
Beekman5 std ppt_13Beekman5 std ppt_13
Beekman5 std ppt_13
Department of Education - Philippines
 
Programming in c++
Programming in c++Programming in c++
Programming in c++
MalarMohana
 
Programming in c++
Programming in c++Programming in c++
Programming in c++
sujathavvv
 
06 fse design
06 fse design06 fse design
06 fse design
Mohesh Chandran
 
design-3 software engineering unit three
design-3 software engineering unit threedesign-3 software engineering unit three
design-3 software engineering unit three
Devendra Meena
 
Waterfall model
Waterfall modelWaterfall model
Waterfall model
LPK Any Komputer
 
Software Engineering with Objects (M363) Final Revision By Kuwait10
Software Engineering with Objects (M363) Final Revision By Kuwait10Software Engineering with Objects (M363) Final Revision By Kuwait10
Software Engineering with Objects (M363) Final Revision By Kuwait10
Kuwait10
 
NEXiDA at OMG June 2009
NEXiDA at OMG June 2009NEXiDA at OMG June 2009
NEXiDA at OMG June 2009
Claudio Rubbiani
 
Day1
Day1Day1
Day1
madamewoolf
 
object oriented programming language in c++
object oriented programming language in c++object oriented programming language in c++
object oriented programming language in c++
Ravikant517175
 
software engineering chapte r one Btech
software engineering chapte  r one Btechsoftware engineering chapte  r one Btech
software engineering chapte r one Btech
VaibhavBhagwat18
 
MPP-UPNVJ
MPP-UPNVJMPP-UPNVJ
MPP-UPNVJ
M. Misdianto, MSc.
 
Design programing logic powor point.pptx
Design programing logic powor point.pptxDesign programing logic powor point.pptx
Design programing logic powor point.pptx
hailish4421ict
 
Programming C ppt for learning foundations
Programming C ppt for learning foundationsProgramming C ppt for learning foundations
Programming C ppt for learning foundations
ssuser65733f
 
unit-iipart-1.WDQWDQWDQWDQWDQWDQWDQWDQWDQWDppt
unit-iipart-1.WDQWDQWDQWDQWDQWDQWDQWDQWDQWDpptunit-iipart-1.WDQWDQWDQWDQWDQWDQWDQWDQWDQWDppt
unit-iipart-1.WDQWDQWDQWDQWDQWDQWDQWDQWDQWDppt
WrushabhShirsat3
 
Ad

Recently uploaded (20)

Providing an OGC API Processes REST Interface for FME Flow
Providing an OGC API Processes REST Interface for FME FlowProviding an OGC API Processes REST Interface for FME Flow
Providing an OGC API Processes REST Interface for FME Flow
Safe Software
 
Oracle Cloud Infrastructure AI Foundations
Oracle Cloud Infrastructure AI FoundationsOracle Cloud Infrastructure AI Foundations
Oracle Cloud Infrastructure AI Foundations
VICTOR MAESTRE RAMIREZ
 
Establish Visibility and Manage Risk in the Supply Chain with Anchore SBOM
Establish Visibility and Manage Risk in the Supply Chain with Anchore SBOMEstablish Visibility and Manage Risk in the Supply Chain with Anchore SBOM
Establish Visibility and Manage Risk in the Supply Chain with Anchore SBOM
Anchore
 
Creating an Accessible Future-How AI-powered Accessibility Testing is Shaping...
Creating an Accessible Future-How AI-powered Accessibility Testing is Shaping...Creating an Accessible Future-How AI-powered Accessibility Testing is Shaping...
Creating an Accessible Future-How AI-powered Accessibility Testing is Shaping...
Impelsys Inc.
 
June Patch Tuesday
June Patch TuesdayJune Patch Tuesday
June Patch Tuesday
Ivanti
 
Scaling GenAI Inference From Prototype to Production: Real-World Lessons in S...
Scaling GenAI Inference From Prototype to Production: Real-World Lessons in S...Scaling GenAI Inference From Prototype to Production: Real-World Lessons in S...
Scaling GenAI Inference From Prototype to Production: Real-World Lessons in S...
Anish Kumar
 
TrustArc Webinar - 2025 Global Privacy Survey
TrustArc Webinar - 2025 Global Privacy SurveyTrustArc Webinar - 2025 Global Privacy Survey
TrustArc Webinar - 2025 Global Privacy Survey
TrustArc
 
The State of Web3 Industry- Industry Report
The State of Web3 Industry- Industry ReportThe State of Web3 Industry- Industry Report
The State of Web3 Industry- Industry Report
Liveplex
 
Viral>Wondershare Filmora 14.5.18.12900 Crack Free Download
Viral>Wondershare Filmora 14.5.18.12900 Crack Free DownloadViral>Wondershare Filmora 14.5.18.12900 Crack Free Download
Viral>Wondershare Filmora 14.5.18.12900 Crack Free Download
Puppy jhon
 
If You Use Databricks, You Definitely Need FME
If You Use Databricks, You Definitely Need FMEIf You Use Databricks, You Definitely Need FME
If You Use Databricks, You Definitely Need FME
Safe Software
 
vertical-cnc-processing-centers-drillteq-v-200-en.pdf
vertical-cnc-processing-centers-drillteq-v-200-en.pdfvertical-cnc-processing-centers-drillteq-v-200-en.pdf
vertical-cnc-processing-centers-drillteq-v-200-en.pdf
AmirStern2
 
No-Code Workflows for CAD & 3D Data: Scaling AI-Driven Infrastructure
No-Code Workflows for CAD & 3D Data: Scaling AI-Driven InfrastructureNo-Code Workflows for CAD & 3D Data: Scaling AI-Driven Infrastructure
No-Code Workflows for CAD & 3D Data: Scaling AI-Driven Infrastructure
Safe Software
 
Oracle Cloud Infrastructure Generative AI Professional
Oracle Cloud Infrastructure Generative AI ProfessionalOracle Cloud Infrastructure Generative AI Professional
Oracle Cloud Infrastructure Generative AI Professional
VICTOR MAESTRE RAMIREZ
 
TimeSeries Machine Learning - PyData London 2025
TimeSeries Machine Learning - PyData London 2025TimeSeries Machine Learning - PyData London 2025
TimeSeries Machine Learning - PyData London 2025
Suyash Joshi
 
National Fuels Treatments Initiative: Building a Seamless Map of Hazardous Fu...
National Fuels Treatments Initiative: Building a Seamless Map of Hazardous Fu...National Fuels Treatments Initiative: Building a Seamless Map of Hazardous Fu...
National Fuels Treatments Initiative: Building a Seamless Map of Hazardous Fu...
Safe Software
 
“Solving Tomorrow’s AI Problems Today with Cadence’s Newest Processor,” a Pre...
“Solving Tomorrow’s AI Problems Today with Cadence’s Newest Processor,” a Pre...“Solving Tomorrow’s AI Problems Today with Cadence’s Newest Processor,” a Pre...
“Solving Tomorrow’s AI Problems Today with Cadence’s Newest Processor,” a Pre...
Edge AI and Vision Alliance
 
Agentic AI: Beyond the Buzz- LangGraph Studio V2
Agentic AI: Beyond the Buzz- LangGraph Studio V2Agentic AI: Beyond the Buzz- LangGraph Studio V2
Agentic AI: Beyond the Buzz- LangGraph Studio V2
Shashikant Jagtap
 
How to Detect Outliers in IBM SPSS Statistics.pptx
How to Detect Outliers in IBM SPSS Statistics.pptxHow to Detect Outliers in IBM SPSS Statistics.pptx
How to Detect Outliers in IBM SPSS Statistics.pptx
Version 1 Analytics
 
Kubernetes Security Act Now Before It’s Too Late
Kubernetes Security Act Now Before It’s Too LateKubernetes Security Act Now Before It’s Too Late
Kubernetes Security Act Now Before It’s Too Late
Michael Furman
 
“State-space Models vs. Transformers for Ultra-low-power Edge AI,” a Presenta...
“State-space Models vs. Transformers for Ultra-low-power Edge AI,” a Presenta...“State-space Models vs. Transformers for Ultra-low-power Edge AI,” a Presenta...
“State-space Models vs. Transformers for Ultra-low-power Edge AI,” a Presenta...
Edge AI and Vision Alliance
 
Providing an OGC API Processes REST Interface for FME Flow
Providing an OGC API Processes REST Interface for FME FlowProviding an OGC API Processes REST Interface for FME Flow
Providing an OGC API Processes REST Interface for FME Flow
Safe Software
 
Oracle Cloud Infrastructure AI Foundations
Oracle Cloud Infrastructure AI FoundationsOracle Cloud Infrastructure AI Foundations
Oracle Cloud Infrastructure AI Foundations
VICTOR MAESTRE RAMIREZ
 
Establish Visibility and Manage Risk in the Supply Chain with Anchore SBOM
Establish Visibility and Manage Risk in the Supply Chain with Anchore SBOMEstablish Visibility and Manage Risk in the Supply Chain with Anchore SBOM
Establish Visibility and Manage Risk in the Supply Chain with Anchore SBOM
Anchore
 
Creating an Accessible Future-How AI-powered Accessibility Testing is Shaping...
Creating an Accessible Future-How AI-powered Accessibility Testing is Shaping...Creating an Accessible Future-How AI-powered Accessibility Testing is Shaping...
Creating an Accessible Future-How AI-powered Accessibility Testing is Shaping...
Impelsys Inc.
 
June Patch Tuesday
June Patch TuesdayJune Patch Tuesday
June Patch Tuesday
Ivanti
 
Scaling GenAI Inference From Prototype to Production: Real-World Lessons in S...
Scaling GenAI Inference From Prototype to Production: Real-World Lessons in S...Scaling GenAI Inference From Prototype to Production: Real-World Lessons in S...
Scaling GenAI Inference From Prototype to Production: Real-World Lessons in S...
Anish Kumar
 
TrustArc Webinar - 2025 Global Privacy Survey
TrustArc Webinar - 2025 Global Privacy SurveyTrustArc Webinar - 2025 Global Privacy Survey
TrustArc Webinar - 2025 Global Privacy Survey
TrustArc
 
The State of Web3 Industry- Industry Report
The State of Web3 Industry- Industry ReportThe State of Web3 Industry- Industry Report
The State of Web3 Industry- Industry Report
Liveplex
 
Viral>Wondershare Filmora 14.5.18.12900 Crack Free Download
Viral>Wondershare Filmora 14.5.18.12900 Crack Free DownloadViral>Wondershare Filmora 14.5.18.12900 Crack Free Download
Viral>Wondershare Filmora 14.5.18.12900 Crack Free Download
Puppy jhon
 
If You Use Databricks, You Definitely Need FME
If You Use Databricks, You Definitely Need FMEIf You Use Databricks, You Definitely Need FME
If You Use Databricks, You Definitely Need FME
Safe Software
 
vertical-cnc-processing-centers-drillteq-v-200-en.pdf
vertical-cnc-processing-centers-drillteq-v-200-en.pdfvertical-cnc-processing-centers-drillteq-v-200-en.pdf
vertical-cnc-processing-centers-drillteq-v-200-en.pdf
AmirStern2
 
No-Code Workflows for CAD & 3D Data: Scaling AI-Driven Infrastructure
No-Code Workflows for CAD & 3D Data: Scaling AI-Driven InfrastructureNo-Code Workflows for CAD & 3D Data: Scaling AI-Driven Infrastructure
No-Code Workflows for CAD & 3D Data: Scaling AI-Driven Infrastructure
Safe Software
 
Oracle Cloud Infrastructure Generative AI Professional
Oracle Cloud Infrastructure Generative AI ProfessionalOracle Cloud Infrastructure Generative AI Professional
Oracle Cloud Infrastructure Generative AI Professional
VICTOR MAESTRE RAMIREZ
 
TimeSeries Machine Learning - PyData London 2025
TimeSeries Machine Learning - PyData London 2025TimeSeries Machine Learning - PyData London 2025
TimeSeries Machine Learning - PyData London 2025
Suyash Joshi
 
National Fuels Treatments Initiative: Building a Seamless Map of Hazardous Fu...
National Fuels Treatments Initiative: Building a Seamless Map of Hazardous Fu...National Fuels Treatments Initiative: Building a Seamless Map of Hazardous Fu...
National Fuels Treatments Initiative: Building a Seamless Map of Hazardous Fu...
Safe Software
 
“Solving Tomorrow’s AI Problems Today with Cadence’s Newest Processor,” a Pre...
“Solving Tomorrow’s AI Problems Today with Cadence’s Newest Processor,” a Pre...“Solving Tomorrow’s AI Problems Today with Cadence’s Newest Processor,” a Pre...
“Solving Tomorrow’s AI Problems Today with Cadence’s Newest Processor,” a Pre...
Edge AI and Vision Alliance
 
Agentic AI: Beyond the Buzz- LangGraph Studio V2
Agentic AI: Beyond the Buzz- LangGraph Studio V2Agentic AI: Beyond the Buzz- LangGraph Studio V2
Agentic AI: Beyond the Buzz- LangGraph Studio V2
Shashikant Jagtap
 
How to Detect Outliers in IBM SPSS Statistics.pptx
How to Detect Outliers in IBM SPSS Statistics.pptxHow to Detect Outliers in IBM SPSS Statistics.pptx
How to Detect Outliers in IBM SPSS Statistics.pptx
Version 1 Analytics
 
Kubernetes Security Act Now Before It’s Too Late
Kubernetes Security Act Now Before It’s Too LateKubernetes Security Act Now Before It’s Too Late
Kubernetes Security Act Now Before It’s Too Late
Michael Furman
 
“State-space Models vs. Transformers for Ultra-low-power Edge AI,” a Presenta...
“State-space Models vs. Transformers for Ultra-low-power Edge AI,” a Presenta...“State-space Models vs. Transformers for Ultra-low-power Edge AI,” a Presenta...
“State-space Models vs. Transformers for Ultra-low-power Edge AI,” a Presenta...
Edge AI and Vision Alliance
 
Ad

Lecture 1 uml with java implementation

  • 1. COSC 1320Please 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/webctpsid/ mmddyya!
  • 2. Introduction to Computer Science IICOSC 1320/6305Lecture 1: Software Engineering and Classes UML, OOA/OOD/JAVA Implementation A TOP DOWN EXAMPLE (Chapter 12)
  • 3. Copyright © 2011 Dept of Computer Science - University of Houston. All rights reserved.7-3
  • 5. Software EngineeringSoftware Engineering is the study of the techniques and theory that support the development of high-quality softwareThe focus is on controlling the development process to achieve consistently good resultsWe want to:satisfy the client – the person or organization who sponsors the developmentmeet the needs of the user – the people using the software for its intended purpose
  • 6. Goals of Software EngineeringSolve the right problemmore difficult than it might seemclient interaction is keyDeliver a solution on time and under budgetthere are always trade-offsDeliver a high-quality solutionbeauty is in the eye of the beholderwe must consider the needs of various stakeholders
  • 8. Development ModelsA development life cycle defines a process to be followed during product developmentMany software development models have been introducedAll of them address the following fundamental issues in one way or another:problem analysis (What?)design (How?)implementationevaluationmaintenance
  • 9. Problem Analysis - WhatWe must specify the requirements of the software system
  • 10. Problem Analysis - WhatWe must specify the requirements of the software systemMust be based on accurate informationVarious techniques:discussions and negotiations with the clientmodeling the problem structure and data flowobservation of client activitiesanalysis of existing solutions and systems
  • 11. Design - HowWe must specify the solutionYou would not consider building a bridge without a designDesign involves determining:the overall software structure (architecture)the key objects, classes, and their relationshipsAlternatives should be considered
  • 12. ImplementationWe must turn the design into functional softwareToo many people consider this the primary act of software developmentMay involve the reuse of existing software components
  • 13. EvaluationWe must verify that the system conforms to the requirementsThis includes, but goes way beyond, testing code with test casesIt is possible to build a system that has no bugs and yet is completely wrong
  • 14. MaintenanceAfter a system is initially developed, it must be maintainedThis includes:fixing errorsmaking enhancements to meet the changing needs of usersThe better the development effort, the easier the maintenance tasks will be
  • 15. The Waterfall ModelOne of the earliest development modelsEach stage flows into the nextDriven by documentationAdvantages:Lays out clear milestones and deliverablesHas high visibility – managers and clients can see the statusDisadvantages:late evaluationnot realistic in many situations
  • 16. The Spiral ModelDeveloped by Barry Boehm in the mid '80sEmbraces an iterative process, where activities are performed over and over again for different aspects of the systemDesigned to reduce the risks involvedContinually refines the requirementsEach loop through the spiral is a complete phase of development
  • 17. The Evolutionary Model***Like the spiral model, an evolutionary approach embraces continual refinementIntermediate versions of the system are created for evaluation by both the developers and the clientMay be more difficult to maintain depending on the attention given to the iterations
  • 18. The Unified Modeling LanguageThe Unified Modeling Language (UML) has become a standard notation for software analysis (OOA) & design (OOD)It is language independentIt includes various types of diagrams (models) which use specific icons and notationsHowever, it is flexible – the details you include in a given diagram depend on what you are trying to capture and communicate
  • 19. UML Class DiagramsUML class diagrams may include:The classes used in the systemThe static relationships among classesThe attributesand operations of each classThe constraints on the connections among objectsAn attributeis class level data, including variables and constantsAn operation is essentially equivalent to a methodMay include visibility details+ public private# protected
  • 20. UML class diagram showing inheritance relationships
  • 21. UML class diagram showing an association
  • 22. One class shown as an aggregate of other classes
  • 23. UML diagram showing a class implementing an interface
  • 24. One class indicating its use of another
  • 25. ObjectivesAdvise on the classSoftware EngineeringProblem solvingMemoryClasses
  • 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 SolvingInitialDesignEdit:typing in the Java code SpecificationCompile:Translating to executable instructions Run:Testing the program to see that it works
  • 28. Life CycleProblem⇒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 CycleProblem⇒ 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 debugimport 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\n", 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: 70Enter next mark: 85Enter next mark: 65Enter next mark: doneaverage mark = 73.33Enter next mark: doneError: divide by zero
  • 32. ObjectivesAdvise on the classSoftware EngineeringProblem solvingMemoryClasses
  • 33. Machine Languages, Assembly Languages, and High-level LanguagesThree types of programming languagesMachine languagesStrings of numbers giving machine specific instructionsExample:+1300042774+1400593419+1200274027Assembly languagesEnglish-like abbreviations representing elementary computer operations (translated via assemblers)Example:LOAD BASEPAYADD OVERPAYSTORE GROSSPAYHigh-level languagesCodes similar to everyday EnglishUse mathematical notations (translated via compilers)Example:grossPay = basePay + overTimePay
  • 34. History of CCEvolved by Ritchie from two previous programming languages, BCPL and BUsed to develop UNIXUsed to write modern operating systemsHardware independent (portable)By late 1970's C had evolved to "Traditional C“StandardizationMany slight variations of C existed, and were incompatibleCommittee formed to create a "unambiguous, machine-independent" definitionStandard created in 1989, updated in 1999
  • 35. The C Standard LibraryC programs consist of pieces/modules called functionsA programmer can create his own functionsAdvantage: the programmer knows exactly how it worksDisadvantage: time consumingProgrammers will often use the C library functionsUse these as building blocksAvoid 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 TechnologyObjects Reusable software componentsthat model items in the real worldMeaningful software unitsDate 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 programmingFavor modularity
  • 37. C++C++Superset of C developed by BjarneStroustrup at Bell Labs"Spruces up" C, and provides object-oriented capabilitiesObject-oriented very powerful10 to 100 fold increase in productivityDominant language in industry and academia
  • 38. JavaJava is used to Create Web pages with dynamic and interactive content Develop large-scale enterprise applicationsEnhance the functionality of Web serversProvide applications for consumer devices (such as cell phones, pagers and personal digital assistants)
  • 39. Other High-level LanguagesOther high-level languagesFORTRANUsed for scientific and engineering applicationsCOBOLUsed to manipulate large amounts of dataPascal Intended for academic use
  • 40. Basics of a Typical C Program Development EnvironmentPreprocessor programprocesses the code.Compiler creates object code and storesit on disk.CompilerLinker links the objectcode with the librariesPrimary MemoryLoaderLoader puts program in memory.Primary MemoryCPU takes eachinstruction and executes it, possibly storing new data values as the program executes. CPUPreprocessorLinkerEditorDiskDiskDiskDiskDisk...... ......Phases of C++ Programs:EditPreprocessCompileLinkLoadExecuteProgram is created inthe editor and storedon disk.
  • 41. Memory ConceptsVariable namesCorrespond to actual locations in computer's memoryEvery variable has name, type, size and valueWhen new value placed into variable, overwrites previous valueReading variables from memory nondestructive
  • 42. Memory Concepts4545724572integer1integer1integer2integer1integer2117sumstd::cin >> integer1;Assume user entered 45std::cin >> integer2;Assume user entered 72sum = integer1 + integer2;
  • 43. Memory927892799280928192829283928492859286Main memory is divided into many memory locations (or cells)Each memory cell has a numeric address, which uniquely identifies it
  • 44. Storing InformationEach memory cell stores a set number of bits (usually 8 bits, or one byte)Large values arestored in consecutivememory locations92789279928092819282928392849285928610011010
  • 45. References38num1"Steve Jobs"name1Note that a primitive variable contains the value itself, but an object variable contains the address of the objectAn object reference can be thought of as a pointer to the location of the objectRather than dealing with arbitrary addresses, we often depict a reference graphically
  • 46. Assignment Revisited38num1Before:96num238num1After:38num2The act of assignment =takes a copy of a value and stores it in a variableFor primitive types:num2 = num1;
  • 47. Reference Assignment"Steve Jobs"name1Before:"Steve Wozniak"name2"Steve Jobs"name1After:name2For object references, assignment copies the address:name2 = name1;
  • 48. Numeric Primitive DataTypebyteshortintlongfloatdoubleStorage8 bits16 bits32 bits64 bits32 bits64 bitsMin Value-128-32,768-2,147,483,648< -9 x 1018+/- 3.4 x 1038+/- 1.7 x 10308Max Value12732,7672,147,483,647> 9 x 1018The difference between the various numeric primitive types is their size, and therefore the values they can store:927892799280928192829283928492859286
  • 54. Software: User ProgramsPrograms 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 togetherDiskRAMCPUCacheOSAppBusPrograms and applications that are not running are stored on disk.
  • 56. Putting it all togetherDiskRAMCPUCacheOSAppAppOSBus When you launch a program, the OS controls the CPU and loads the program from disk to RAM.
  • 57. Putting it all togetherDiskRAMCPUCacheOSAppAppAppBusThe OS then relinquishes the CPU to the program, which begins to run.
  • 58. The Fetch-Execute CycleAs the program runs, it repeatedly fetches the next instruction (from memory/cache), executes it, and stores any results back to memory.DiskRAMCPUCacheOSAppAppAppBusThat’s all a computer does: fetch-execute-store, millions of times each second!
  • 60. OverviewUnderstand Classesand Objects.Understand some of the key concepts/features in the Object Oriented paradigm.Benefits of Object Oriented paradigm.
  • 61. OOP: Model, map, Reuse, extendModel the real world problem to user’s perceiveUse similar metaphor in computational env.Construct Reusable componentsCreate new components from existing ones.
  • 63. Classes :Objectswith the same attributes and behavior
  • 64. Object Oriented Paradigm: FeaturesEncapsulationData AbstractionSingle InheritanceOOP ParadigmPolymorphismPersistenceDelegationGenericityMultiple Inheritance
  • 65. Java’s OO FeaturesEncapsulationData AbstractionSingle InheritanceJavaOOP ParadigmPolymorphismPersistenceDelegationGenericityMultiple Inheritance
  • 66. EncapsulationAssociates the Code & the Datait manipulates into a single unit; and keeps them safe from external interference and misuse.EncapsulationData AbstractionSingle InheritanceOOP ParadigmPolymorphismPersistenceDelegationDataGenericityCodeMultiple Inheritance
  • 67. Data AbstractionThe 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).EncapsulationData AbstractionSingle InheritanceOOP ParadigmPolymorphismPersistenceDelegationGenericityMultiple 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 - Exampleclass Account { private StringaccountName;privatedoubleaccountBalance;publicwithdraw();publicdeposit();public determineBalance();} // Class Account
  • 71. ClassClass is a set of attributesand operations that are performed on the attributes.StudentCircleAccountaccountNameaccountBalancenameagestudentIdcentreradiuswithdraw()deposit()determineBalance()area()circumference()getName()getId()
  • 72. ObjectsAn Object Oriented system is a collection of interacting Objects.Objectis an instance of a class.
  • 73. Classes /ObjectsJohn and Jill are objects of classStudent:JohnStudent:Jill:circleAcircleA and circleB are objects of classCircleCircle:circleB
  • 74. ClassA 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. ObjectObjects have state and classes don’t.Johnis an object (instance) of class Student. name = “John”, age = 20, studentId = 1236Jill is an object (instance) of class Student. name = “Jill”, age = 22, studentId = 2345circleAis an object (instance) of class Circle. centre = (20,10), radius = 25circleB is an object (instance) of class Circle. centre = (0,0), radius = 10
  • 76. EncapsulationAll 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 - ExamplemessagewithdrawdepositaccountBalancemessagedetermine Balancemessageclass Account { privatedoubleaccountBalance;public withdraw();public deposit();public determineBalance();} // Class Account
  • 78. Data AbstractionThe 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 - Exampleclass Account { private String accountName; private double accountBalance; public withdraw(); public deposit(); public determineBalance();} // Class Account Creates a data type AccountAccountacctX;
  • 80. InheritanceParentChildNew 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 - ExampleExamplesDefine Person to be a classA Person has attributes, such as age, height, genderAssign values to attributes when describing objectDefine 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 PersonDefine lecturer to be a subclass of Personlecturer has all attributes of Person, plus attributes of his/her own (staff_id, subjectID1, subjectID2)
  • 82. Inheritance - ExampleCircle Class can bea subclass (inheritedfrom) of a parent class - ShapeShapeCircleRectangle
  • 83. Inheritance - ExampleInheritance can also have multiple levels.ShapeCircleRectangleGraphicCircle
  • 84. Uses of Inheritance - ReuseIf 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 - ReuseCirclecentreradiusarea()circumference()move(newCentre)move(newCentre){centre = newCentre;}Rectanglecentreheightwidtharea()circumference()move(newCentre)move(newCentre){ centre = newCentre;}move(newCentre){centre = newCentre;}
  • 86. 86Uses of Inheritance - ReuseShapecentremove(newCentre){centre = newCentre}area()circumference()move(newCentre)RectangleCircleheightwidthradiusarea()circumference()area()circumference()
  • 87. Uses of Inheritance - SpecializationSpecialized 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. 88Circlecentreradiusarea()circumference()move(newCentre)area(){ return pi*r^2;}Uses of Inheritance - SpecializationRectanglecentreheightwidtharea()circumference()move(newCentre)area(){ return height*width;}
  • 89. 89Uses of Inheritance - Specializationarea(){ return pi*r^2;}Shapecentrearea(); - not implemented and left for the child classesto implementarea()circumference()move(newCentre)RectangleCircleheightwidthradiusarea()circumference()area(){ return height*width;}area()circumference()
  • 90. Uses of Inheritance – Common InterfaceAll 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 - ExtensionExtend 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 - ExtensionShapecentrearea()circumference()move(newCentre)RectangleCircleheightwidthradiusarea()circumference()rotate90degrees()area()circumference()
  • 93. Uses of Inheritance – Multiple InheritanceInherit properties from more than one class. This is called Multiple Inheritance.ShapeGraphicsCircle
  • 94. Uses of Multiple InheritanceThis 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 InheritanceShapecentrearea()circumference()move(newCentre)Circleradiusarea()circumference()GraphicCirclecolorpaint()
  • 96. PolymorphismPolymorphic which means “many forms” has Greek roots.Poly – manyMorphos - 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 beexecutedrectangleA = new Rectangle(); Create a new rectangle objectshape= rectangleA;shape.area()area() method for rectangle will be executed.
  • 98. Polymorphism – Method OverloadingMultiple 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. 99Polymorphism – Operator OverloadingAllows regular operators such as +, -, *, / to have different meanings based on the type.e.g. + operator for Circle can re-definedCircle c = c + 2;Not supported in JAVA. C++ supports it.
  • 100. 100PersistenceThe 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. 101Why OOP? Greater ReliabilityBreak complex software projects into small, self-contained, and modular objectsMaintainabilityModular objects make locating bugs easier, with less impact on the overall projectGreater 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. SummaryObject Oriented Analysis, Design, and Programming is a Powerful paradigmEnables Easy Mapping of Real world Objects to Objects in the ProgramThis is enabled by OO features:EncapsulationData AbstractionInheritancePolymorphismPersistenceStandard OO Analysis and Design (UML) and Programming Languages (C++/Java) are readily accessible.
  • 106. What We Will Learn?How to solve a problem.Using JavaJava is a good language to start doing object oriented (OO) in because it attempts to stay true to all the different OO paradigms.Copyright © 2011 Dept of Computer Science - University of Houston. All rights reserved.
  • 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.OOPPPVariablesDataFunctionsMethodsClass
  • 108. Example programDesign and Implement a program to calculate perimeter of a circle.PPCOOPJavaCopyright © 2011 Dept of Computer Science - University of Houston. All rights reserved.7-108CLASS Participation A!
  • 109. Example program, PP in CDesign and ImplementPPVariablesFunctionsDriver.c#include <iostream>const double PI=3.14;void main(){doublecircleRadius = 10;double circlePerimeter = 2*PI*circleRadius;printf("Circle Perimiter%f\n",circlePerimeter);system("pause");}CLASS Participation B!
  • 110. Copyright © 2011 Dept of Computer Science - University of Houston. All rights reserved.7-110CLASS Participation B!
  • 111. Example program, OOP in Java7-111The core of OOP: “Put related things together.”Design Implement Circle.javapublic 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.javapublic classMain {public static void main(String[] args) { Circle circle = new Circle(10);System.out.println("Circle Perimeter " + circle.getPerimeter());}}DataOOPMethods
  • 112. Copyright © 2011 Dept of Computer Science - University of Houston. All rights reserved.7-112
  • 113. Example program, PP in CDesign and ImplementPPVariablesFunctionsDriver.c#include <iostream>const double PI=3.14;void main(){doublecircleRadius = 10;double circlePerimeter = 2*PI*circleRadius;printf("Circle Perimiter%f\n",circlePerimeter);system("pause");}CLASS Participation B!
  • 114. Copyright © 2011 Dept of Computer Science - University of Houston. All rights reserved.7-114CLASS Participation B!
  • 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: UMLUnified 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 LanguageUMLprovides 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 DiagramsThe 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 DiagramsWe 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 system1. 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 DiagramsDrawing Use Case Diagrams1. 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 ItemUse Case 1Use Case 2Use Case 3Use Case 4
  • 121. 2. UMLClass DiagramsThe 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 DiagramsNotice 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 DiagramsClass 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.javaIn UMLrelationships are presumed to be bidirectional unless the arrowhead is present to restrict them.
  • 124. 2. UML Class DiagramsComposition 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 DiagramsThe 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 DiagramsAnother 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.
  • 127. Candy Machine Case StudyRequirementsTextual AnalysisUML Modeling
  • 128. UMLClass DiagramSimplified methodology1. Write down detailed description of problem2. Identify all (relevant) nouns and verbs3. From list of nouns, select objects4. Identify data components of each object5. From list of verbs, select operations
  • 129. UMLClass DiagramA 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 machineLet the customermakethe selectionShowthe customerthe cost of the item selectedAcceptmoney from the customerReturn changeRelease the item; that is, makethe saletextual analysis
  • 130. UMLClass DiagramTextual AnalysisPlace, 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 AnalysisYou 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 AnalysisDispenser 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  cashOnHandCandy 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 DiagramDispenser 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 DiagramCash Register The cash register accepts money and returns change. Therefore, the cash register has only one data member, which we call  cashOnHand
  • 136. UMLClass DiagramCandy 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 DiagramThe 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 DiagramThe 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 DiagramThe 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 DiagramSimilarly, 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 DiagramDetailed Design Pseudocode for showSelectionmethodShow the selection to the customerGet selectionIf selection is valid and the dispenser corresponding to the selection is not empty, sell the product
  • 143. UMLClass DiagramDetailed Design Pseudocode for makeSalemethodIf the dispenser is nonempty:Prompt customer to enter the item costGet the amount entered by the customerIf the amount entered by the customer is less than the cost of the productPrompt customer to enter additional amountCalculate total amount entered by the customerIf amount entered by the customer is at least the cost of the productUpdate the amount in the cash registerSell the product; that is, decrement the number of items in the dispenser by 1Display an appropriate messageIf amount entered is less than cost of itemReturn the amountIf the dispenser is emptyTell the customer that this product is sold out
  • 144. UMLClass DiagramDetailed Design Pseudocode for main methodDeclare a variable of type cashRegisterDeclare and initialize four objects dispenserTypeFor 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 DiagramDetailed Design Pseudocode for main methodDeclare additional variables as necessaryShow menuGet the selectionWhile not done (9 exits)Sell product (sellProduct)Show selection (showSelection)Get selection
  • 146. Case Study: Candy Machine Implementation - JAVACLASS Participation C!
  • 147. Case Study: Candy Machine Implementation- JAVA
  • 148. Case Study: Candy Machine Implementation- JAVA
  • 149. JAVA
  • 150. Video Store Case StudyRequirementsTextual AnalysisUML ModelingCopyright © 2011 Dept of Computer Science - University of Houston. All rights reserved.7-150
  • 151. OO Analysis & OO Design and Implement in JAVARequirementsA 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 AnalysisActor: 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 CASESBefore 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 AnalysisActor: 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 CASESBefore 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 EmployeeUse Case 1 : Scan Membership Card
  • 154. UMLUse Case Diagram – Textual AnalysisActor: 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 CASESBefore 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 EmployeeUse Case 1 : Scan Membership CardA 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 AnalysisActor: 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 CASESBefore 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 EmployeeUse Case 1: Scan Membership CardA 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 EmployeeUse Case 2 : Scan Video Medium
  • 156. UMLUse Case Diagram – Textual AnalysisActor: 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 CASESBefore 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 EmployeeUse Case 1 : Scan Membership CardA 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 EmployeeUse Case 2 : Scan Video MediumCustomer 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 AnalysisActor: 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 CASESBefore 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 EmployeeUse Case 1 : Scan Membership CardA 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 EmployeeUse Case 2 : Scan Video MediumCustomer pays the nominal fee before the video can be rented out. The payment may be with cash or debit/credit card. Actors : Customer and EmployeeUse Case 3, 4 : Accept Payment and Charge Payment to Card
  • 158. UMLUse Case Diagram – Textual AnalysisUSE CASESBefore 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 EmployeeUse Case 1 : Scan Membership CardA 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 EmployeeUse Case 2 : Scan Video MediumCustomer pays the nominal fee before the video can be rented out. The payment may be with cash or debit/credit card. Actors : Customer and EmployeeUse Case 3, 4 : Accept Payment and Charge Payment to CardThe 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 AnalysisUSE CASESBefore 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 EmployeeUse Case 1 : Scan Membership CardA 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 EmployeeUse Case 2 : Scan Video MediumCustomer pays the nominal fee before the video can be rented out. The payment may be with cash or debit/credit card. Actors : Customer and EmployeeUse Case 3, 4 : Accept Payment and Charge Payment to CardThe 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 EmployeeUse Case 5 : Print Receipt
  • 160. An Example: UML Use Case Diagram
  • 163. An Example: What is next?Use Case ViewUse Case DiagramStructural ViewClass DiagramObject DiagramComposite Structure DiagramBehavioral ViewSequence DiagramCommunication DiagramState DiagramActivity DiagramInteraction Overview DiagramTiming DiagramImplementation ViewComponent DiagramComposite Structure DiagramEnvironment ViewDiagram
  • 164. UML Activity Diagram – Textual AnalysisActivity 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 caseShows the steps of computationWe need to find actions (steps) in use case flows.
  • 165. Finding actions in use case – Textual Analysis1. 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 detailsAction 2: Key in cash amountAction 3: Confirm transactionAction 4: Swipe the cardAction 5: Accept card numberAction 6: Select card accountAction 3: Confirm transaction
  • 166. Finding actions in use case – Textual Analysis4. 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 manuallyAction 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 AnalysisActivity diagram shows transitions between actions.Transitions can branch and mergeAction 1: Display transaction detailsAction 4: Swipe the cardAction 5: Accept card numberAction 6: Select card accountAction 3: Confirm transactionAction 2: Key in cash amountAction 3: Confirm transactionAction 7: Enter card number manuallyAction 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 ViewUse Case DiagramStructural ViewClass DiagramObject DiagramComposite Structure DiagramBehavioral ViewSequence DiagramCommunication DiagramState DiagramActivity DiagramInteraction Overview DiagramTiming DiagramImplementation ViewComponent DiagramComposite Structure DiagramEnvironment ViewDiagram
  • 171. UML Class Diagram – Textual AnalysisClass modeling captures the static view of the system although it also identifies operations that act on data. Class modeling elementsClasses themselvesAttributes (data)and operations (methods) of classesRelationships - associations, aggregation and composition, and generalization.Class diagram is a combined visual representation for class modeling elements.Assignment of use cases to classesFINDING 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 AnalysisBefore 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 AnalysisBefore 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 AnalysisBefore 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,MembershipCardA 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 AnalysisBefore 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,MembershipCardA 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.VideoTapeVideoDisk,Customer,Rental
  • 176. UML Class Diagram – Textual AnalysisBefore 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,MembershipCardA 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.VideoTapeVideoDisk,Customer,RentalCustomer 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 AnalysisClasses?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,MembershipCardA 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.VideoTapeVideoDisk,Customer,RentalCustomer 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 AnalysisClasses?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,MembershipCardA 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.VideoTapeVideoDisk,Customer,RentalCustomer pays the nominal fee before the video can be rented out. The payment may be with cash or debit/credit card. Customer,Video,Rental,PaymentThe system verifies all conditions for renting out the video, acknowledges that the transaction can go ahead, and can print the receipt for the customer.
  • 179. UML Class Diagram – Textual AnalysisClasses?Classes?Classes?Classes?Video,Customer,MembershipCardVideoTapeVideoDisk,Customer,RentalCustomer,Video,Rental,PaymentRental,Receipt
  • 180. UML Class Diagram – Textual Analysis
  • 182. UML Class Diagram– Attributes– Textual AnalysisIdentifying attributesfor each classAttributes 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.
  • 183. C2C3