0% found this document useful (0 votes)
12 views477 pages

Slides 15.12.2023

The document discusses the importance of object-oriented design and programming in addressing challenges in software engineering, emphasizing that merely using object-oriented programming languages does not guarantee success. It highlights the complexities involved in software development, including issues related to user requirements, communication gaps, and the evolving nature of technology. Additionally, it outlines the structured approach needed for successful software development, including analysis, design, and adherence to best practices.

Uploaded by

piyushjain76296
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
12 views477 pages

Slides 15.12.2023

The document discusses the importance of object-oriented design and programming in addressing challenges in software engineering, emphasizing that merely using object-oriented programming languages does not guarantee success. It highlights the complexities involved in software development, including issues related to user requirements, communication gaps, and the evolving nature of technology. Additionally, it outlines the structured approach needed for successful software development, including analysis, design, and adherence to best practices.

Uploaded by

piyushjain76296
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 477

CS 201:

Object Oriented Design


and Programming

Pramit Mazumdar
12/15/2023 1
Challenges in Software Engineering
 Why is it important to study object orientation?

 How does it correlates with solving real life


problems?

 How it can be used in the design of a complex


software?

12/15/2023 2
Challenges in Software Engineering
 Complex Software:

 Analysis
 Design
 Implementation
 Maintenance

 Object oriented programming languages are of


great help

 Such as Java, C++, Python etc.

 Advantages: OOPLs have definition, creation,


destruction, management, etc.

12/15/2023 3
Challenges in Software Engineering
 However, mere use of a OOPL does not guarantee
the above

 There are various level of problems that are faced


during software engineering

 Problems encountered by the software systems


 Problems encountered by the developers
 Problems encountered by the users of the software systems

 Solution to such problems cannot be addressed by


just learning and using the OOPL !!!

12/15/2023 4
Challenges in Software Engineering
 Most of the problems start at the specification
level

 Where users fail to understand what they want

 Understanding the expectations and clearly


describing them to the developer (enterprise) is
important

 Sometimes softwares are specific to a person or


organization

 In this case the specifications are defined by users

12/15/2023 5
Challenges in Software Engineering
 Similarly there are software which are generic in
nature

 For example MS PowerPoint/ Excel/ Word, etc.

 This is more challenging as multiple users round


the globe have multiple requirements and they are
fused together meticulously to give a proper user
experience

 In both the scenarios; specification, design,


analysis, implementation, maintenance, etc. is
important.

12/15/2023 6
Challenges in Software Engineering
 Typically a software engineering is responsible for
engineering a software that can be used and liked
by the end users

 Remember: Software is DEVELOPED not


CONSTRUCTED

 This is unlike any other Engineering domain !!

 Civil = constructs buildings


 Mechanical = constructs automobiles
 Electrical = constructs power plants
 Software = develops a software !!

12/15/2023 7
Challenges in Software Engineering
 According to Standish Group’s Annual CHAOS report, 66%
of technology projects (based on the analysis of 50,000
projects globally) end in partial or total failure*

 Just one in three software projects are considered truly


successful with large projects most at risk of failure.

12/15/2023 * https://www.atlascode.com/blog/why-software-projects-fail/ 8
Why Software Fails !!
 COMPLEXITY …. complexity in various domain

 RESOURCES … creator of many problems

 Changes from Requirements


 Customers learn from software
 Requirement changes as Prototype is shown
 Customers do not know what they want !!!
 Business environment changes
 Business condition changes
 Process of Business changes

 Changes from Technology


 Software is not standalone
 It depends upon hardware, OS, network component, etc.
 Over time technology evolves
 The system from which one started the project may end up into an obsolete system!!

12/15/2023 9
Why Software Fails !!
 Changes from People
 Usually the process of constructing something can be automated

 However in software the process of development is difficult to


automate

 For example it is difficult to automate writing of codes

 Ultimately it is the people or developers who write the code

 Complexity starts from here

 Developer changes

 Multiple developers may not agree to an approach

 One may not follow the approach followed by an ex-developer of the same
project

 Etc.

12/15/2023 10
Software Engineering
 Is Software engineering

 A manufacturing process, or

 A designing of a manufacturing or service oriented process

 The process of designing is an innovative process

 It is not a predictive or automated process

 Requires a great deal of Communication /


Understandability / Innovation, etc.

12/15/2023 11
Target
 Software Development -> Software Construction

 In future can we

 Construct a software

 Confidence that the constructed software would work

 The process of construction would be predictable

 The quality of the software would be predictable

 The cost of software development would be predictable

12/15/2023 12
Target
 Current SOA says that to achieve the above we
need

 Structured analysis

 Modelling

 Design

 Implementation

 Adherence to good practices.

12/15/2023 13
Why this course
 Object Oriented Analysis and Design

 It is a precursor to the previously mentioned


requirements

 Understanding the basics of OOAD can help in


formulating the development process of a software

 There are topics in OOAD which can directly help


to address problems faced by developers while
developing a software.

12/15/2023 14
Types of Software
 Personal or limited use Software

 Industrial-strength Software

 Personal or Limited use Software

 Limited set of behaviors


 Not very complex
 Developed, maintained and used by the same person or group
 Short life span
 Demonstration purpose
 Not expected to be lasting forever
 Presence of small bugs is not of concern
 Lack of quality.

12/15/2023 15
Types of Software
 Industrial-strength Software

 It refers to a software which have rich set of behaviors

 Well planned in accordance with the user requirements

 Works with limited resources

 Maintains the integrity of millions of records while allowing


concurrent updates and queries

 Commands and controls a real-world problem

 Long life-span

 Complexity of such software exceeds the human intellectual


capacity.

12/15/2023 16
Software Complexities
 The complexity of the problem domain

 The difficulty of managing the development


process

 The flexibility possible through a software

 The problems of characterizing the behavior of


discrete systems.

12/15/2023 17
Problem domain
 Domains are difficult to understand

 Functional requirements are complex to


understand

 Non-functional requirements (non-evident) are


also complex to predict in advance

 Usability
 Performance
 Cost
 Survivability
 Reliability
 Users do not understand the non-functional requirements
 Implicit in nature !!

12/15/2023 18
Problem domain
 Communication gap between Users and
Developers

 The greatest bottleneck in a software development process

 Users cannot express and Developers cannot understand

 Different perspective of the problem in hand (different


assumptions).

 Changing or evolving requirements

 More requirements comes up with better understanding of the


prototype

 Developers often gets enlightened through the process of


development.

12/15/2023 19
Managing the Development Process
 Illusion of Simplicity

 Hide external complexity


 Code bases get large
 Software should give the illusion to the user that the task which
he/she performed is extremely easy
 Whereas the backend code base is having a very complex logic,
which is abstracted from the user !

 Increase in code-base requires involvement of more


people in the project

 As it is impossible for a single person to run the large


code-base.. That’s why a Software development process
requires a Team !!

12/15/2023 20
Flexibility possible through a Software
 Components required to build a Software is not
readily available

 There is no standardization on how to build a


software

 Often the components required are also software

 Interestingly, software is such an element which may


require additional features after it has been deployed

 Such flexibility is Excellent, but brings a lot of


complexity.

12/15/2023 21
Behavior of Discrete system
 Discrete system changes its state abruptly at
discrete points, consists of multiple states

 Software are built and executed on digital


computers – thus on Discrete systems

 A software can have infinite number of states

 Various activities to be performed by the software


corresponds to the different states

 These states are often interactable and influenced


by external factors.

12/15/2023 22
Behavior of Discrete system

12/15/2023 23
Behavior of Discrete system

12/15/2023 24
Complex systems are Hierarchic

PC

CPU HDD Mouse KeyB

ALU Memory Bus

Registers

Gates

12/15/2023 25
Complex systems are Hierarchic
 Each level of hierarchy represents a Layer of
abstraction

 Task of CPU is independently understood

 How CPU performs a task is not known

 ALU -> Registers -> Gates have their own tasks


defined

 But they do not know the overall idea or the bigger


picture

 This is known as Emergent Behaviour.


12/15/2023 26
Complex systems are Hierarchic
 Layers in the hierarchy shows emergent behaviour

 Behaviour of the whole is greater than the sum of


its parts

 Behaviour of CPU is greater than the sum of its


parts (ALU, Memory, etc.)

 Interlinked behaviour of the individual parts in a


lower level of hierarchy defines the broad task of a
component (at higher level of hierarchy).

12/15/2023 27
Complex systems are Hierarchic
 All systems are composed of interrelated sub-
systems

 Sub-systems are composed of sub-sub systems ..

 Lowest level sub-systems are composed of


elementary components

 All systems are parts of larger systems

 Users only understands a system which is at a


higher level of hierarchy !!

12/15/2023 28
Five attributes of a Complex system
 Hierarchic structure

 Relative primitives
 Primitives – section of code which can be used to develop
more sophisticated modules

 Strong separation of concerns among the elements

 Common patterns across the elements

 Stable intermediate forms.

12/15/2023 29
Relative properties
 Primitives are chosen by the developer

 It is a Subjective choice

 Strongly depends on the experience and expertise


of the designer

 A primitive chosen by a developer may be


completely abstract for another.

12/15/2023 30
Separation of Concerns
 Hierarchic systems are
 Decomposable = consists of independent elements, so can be
decomposed

 Nearly decomposable = consists of all non-independent elements,


so cannot be decomposed

 Linkages /associations / dependencies between


elements in a hierarchy is important

 Intra-component linkage involves internal structure of


components. Interaction is stronger within component

 Inter-component linkage involves interaction among


components. Interaction is weaker across component.

12/15/2023 31
Common Patterns
 Processor is found in computers, cars, mobiles,
etc.

 If we understand the working of a processor, it is


easier to map how computers, cars, mobiles, etc.
performs

 Most complex systems have common patterns

 Such common patterns are one important aspect


of OOAD

 Common patterns can become a premitive.

12/15/2023 32
Stable Intermediate Forms
 It is extremely difficult to design a complex system
correctly in one go

 Iterative refinement is the approach considered to


be helpful in a software development process

 A complex system is always build from a simple


system which worked .. Prototypes !!.

12/15/2023 33
Types of Complexities
 Organized (Canonical Form)

 Decomposition hierarchy
 Abstraction hierarchy
 Class and object structure
 Canonical form

 Disorganized

 Limited human capacity

12/15/2023 34
Organized Complexity
 We are able to find a structure

 We are able to find some common patterns

 Easy to device tools and mechanism to approach


the problem in a better way

 This leads to a standardized form or a canonical


form of a complex system

12/15/2023 35
Limitation of Human Capacity for Dealing Complexity

 Huge chunk of information is required to be processed for


designing a complex system

 Human processing capacity is limited

 Processing speed is limited

 Group of individuals as a team may help

 Groups brings new challenges with them

 This leads to Disorganized Complexity.

12/15/2023 36
Types of Hierarchy
 We know that complex systems are hierarchical in
nature

 Hierarchies that are mostly used in a OOAD are;

 Decomposition = part-of / has-a

 Abstraction = is-a

 Decomposition refers to part-of / has-as


relationship between components

 Abstraction refers to is-a relationship between


components.

12/15/2023 37
Decomposition Hierarchy

PC

CPU HDD Mouse KeyB

ALU Memory Bus

Registers

Gates

12/15/2023 38
Decomposition Hierarchy
 PC can be broken down to components such as
CPU, HDD, Mouse, Keyboard, etc.

 CPU can also be broken down to ALU, Memory,


Bus, etc.

 If such is the relationship between the


components in a hierarchy then we refer it as
Decomposition hierarchy

 PC has-a CPU. PC has-a HDD. CPU has-a ALU.

12/15/2023 39
Abstraction Hierarchy

CPU

Pentium Pentium II Pentium + MMX

Celeron …. ….

12/15/2023 40
Abstraction Hierarchy
 Specialization of CPU is not mentioned in previous
example

 We never mentioned the type of CPU or the type of


processor

 CPU can be
 Pentium
 Pentium + MMX
 Celeron

 All processors have different details

 But they share the same functionality of a CPU.

12/15/2023 41
Abstraction Hierarchy
 Pentium is-a CPU

 Celeron is-a Pentium + MMX

 Pentium + MMX is-a Pentium

 Pentium + Multimedia extension is similar to a


Pentium with some added functionality

 So Pentium has many variations but they share


the same concept or functionality to some extend

 Such hierarchy among components are known as


the Abstraction hierarchy.
12/15/2023 42
Class and Object Structures
 Hierarchies are referred to as:

 Class structure: Abstraction (IS-A)

 Object structure: Decomposition (HAS-A)

 Complex systems representation has two


orthogonal access; one about abstraction
hierarchy and the other talks about the
decomposition hierarchy

12/15/2023 43
Decomposition Hierarchy

PC

CPU HDD Mouse KeyB

ALU Memory Bus

Registers

Gates

12/15/2023 44
Abstraction Hierarchy

CPU

Pentium Pentium II Pentium + MMX

Celeron …. ….

12/15/2023 45
Abstraction Hierarchy
 Specialization of CPU is not mentioned in previous
example

 We never mentioned the type of CPU or the type of


processor

 CPU can be
 Pentium
 Pentium + MMX
 Celeron

 All processors have different details

 But they share the same functionality of a CPU.

12/15/2023 46
Abstraction Hierarchy
 Pentium is-a CPU

 Celeron is-a Pentium + MMX

 Pentium + Multimedia extension is similar to a


Pentium with some added functionality

 So Pentium has many variations but they share


the same concept or functionality to some extend

 Such hierarchy among components are known as


the Abstraction hierarchy.

12/15/2023 47
Class and Object Structures

12/15/2023 48
Class – Abstraction – IS-A relationship
 Class structure shows IS-A relationship

 Class structure shows Abstraction

 Example:

 C1 = CPU
 C2 = Pentium
 C3 = Mac
 C7 = Celeron

 IS-A relationship is represented by

 Celeron Pentium

12/15/2023 49
Class – Abstraction – IS-A relationship
 Celeron IS-A Pentium

 Celeron includes the properties that Pentium has

 Pentium may has more properties than Celeron

 Pentium can be defined by the various properties that


Celeron has

 Similarly, Pentium IS-A CPU means Pentium has all the


properties that a CPU has (or the properties which defines a
CPU)

 Thus when we look into the system in terms of the


commonality of behavior then we say that it is a Class
structure representing Abstraction.

12/15/2023 50
Decomposition Hierarchy

PC

CPU HDD Mouse KeyB

ALU Memory Bus

Registers

Gates

12/15/2023 51
Decomposition Hierarchy
 PC can be broken down to components such as
CPU, HDD, Mouse, Keyboard, etc.

 CPU can also be broken down to ALU, Memory,


Bus, etc.

 If such is the relationship between the


components in a hierarchy then we refer it as
Decomposition hierarchy

 PC has-a CPU. PC has-a HDD. CPU has-a ALU.

12/15/2023 52
Object – Decomposition – HAS-A relationship

12/15/2023 53
Object – Decomposition – HAS-A relationship

 Dotted lines represents an entity

 An entity consists of multiple sub-entities

 Thus the bigger entity can be broken down or decomposed


into smaller or sub-entity

 So we can look into the system in the form of which is the


bigger component and what are the sub-component with
which it is developed.

12/15/2023 54
Canonical Form of a Complex System

 System Architecture shows how a Complex system looks like

 In term of class abstraction and object decomposition

 If a complex system can be represented in terms of the five


attributes
 Hierarchic structure
 Relative primitives
 Separation of concerns
 Common patterns
 Stable intermediate forms

 Then we can say that the complex system is being designed


in a CANONICAL FORM.

12/15/2023 55
Canonical Form of a Complex System

12/15/2023 56
The Role of Decomposition

 We need to understand that given a complex system how


should be approach to design a decomposition hierarchy

 There are two approaches:

 Algorithmic approach for Decomposition

 Object-oriented approach for Decomposition

 Algorithmic approach

 Top-down structured design

 Divide-and-conquer

 Decompose the problem into key processing steps.

12/15/2023 57
Algorithmic Decomposition

 Involves structured decomposition of individual components.

12/15/2023 58
Object-oriented Decomposition

 Here we do not look into the task in hand

 We look for the key abstractions that are required in the


task

 Decompose the system based on the identified abstractions

 The abstractions can also be called as Agents.

12/15/2023 59
Object-oriented Decomposition

12/15/2023 60
Object-oriented Decomposition

 Each one of them is a key concept or key abstraction

 Remember the arrow direction

 Master File can get formatted update from the File Updates
abstraction

 Object-oriented decomposition is distinct w.r.t Algorithmic


approach

 Object-oriented approach views the system as autonomous


agents that collaborate to perform some higher-level
behaviour

 “Autonomous agents” = active entities that can behave on


their own.

12/15/2023 61
Object-oriented Decomposition

 Each autonomous entity in the previous example are


Objects

 Master File can get formatted update from the File Updates
object

 “get formatted update” becomes an operation that is associated with the


object “File of Updates”

 By calling a function “get formatted update” on “File of Updates” it creates


another object called “Update to Cards”

 Each object in an object-oriented decomposition holds its


own behaviour

 Objects are tangible entity that exhibits some well-defined


behaviour.

12/15/2023 62
Object-oriented Decomposition

 Object do things … or things in a designing process is being


done by using Objects .. As they are autonomous and have
well-defined behaviour

 Objects communicate among themselves

 They communicate by sending messages among each other

 These are the advantages achieved if the complex system is


designed using an object-oriented approach and not an
algorithmic approach.

12/15/2023 63
Object-oriented Decomposition

Objects
Objects

Objects

12/15/2023 64
Objects provides services

f21 f22
O1 O2
f11
f23
f12
f31 f32
O3
f33

f34

12/15/2023 65
Objects communicate among themselves

f21 f22
O1 O2
f11 <O2:f23> f23
f12

f32
O3
f31
f33
Service should
f34 preserve concurrency

12/15/2023 66
Object-Oriented Decomposition

 Objects have a certain behaviour

 Objects provides services

 Services are provided by objects may require communication


with other objects

 Communication is performed by objects via message sending

 Therefore;
 Objects can perform multiple tasks or services or operations

 Objects transmit messages to communicate with other objects.

 Objects are Clients and calling functions/methods are


communication between objects.

12/15/2023 67
Evolution of Design Methods

 Top-down structured design

 Data-driven design

 Object-oriented design

12/15/2023 68
Top-down structured design

 Oldest and most traditional

 Does not address the issues of data abstraction and


information hiding

 Does not provide an adequate means of dealing with


concurrency

 Does not scale up well for extremely complex systems

 Is largely inappropriate for use with object-based and object-


oriented programming languages.

12/15/2023 69
Data-driven design

 Mapping system inputs to the outputs

 The above strategy derives the structure of a software


system

 It has been successfully applied to multiple complex


domains (specially Information management systems)

 However, they are less effective for time-critical events

 In certain Information management systems where time


constraint is absolutely important, this design approach
cannot be applied

 For example, breaking system in a Car.

12/15/2023 70
Object-oriented design

 Models software systems as collections of cooperating


objects

 Treats individual objects as instances of a class within a


hierarchy of classes

 OOAD directly reflects the topology of a high-order


programming languages such as Java/ C++.

12/15/2023 71
Algorithmic vs Object oriented Decomposition

Algorithmic Object-oriented
Highlights the ordering of events Emphasizes on Agents (clients /
servers)
Typically develops Larger Systems Yields smaller systems by reusing
methodologies
Lower re-usability characteristics Large re-usability characteristics

Less resilient and more risky to build More resilient to change and reduces
complex systems risk of building complex systems
Unable to reduce complexity By following the approach of
“separation of concerns” is reduces
the complexity of a system
significantly
Low concurrency High concurrency and Distributed in
nature.

12/15/2023 72
Abstraction

 Abstraction is another important strategy along with


Decomposition which helps in a proper designing of a
complex system

 Human brain has limitations: storage problem, unable to


process all information, sequentially receiving information,
and everything needs to be done in a time-bound way

 Abstraction typically says you look into only those


information which you need

 There is no need to know the underlying structure, as it is


not immediately needed for processing

 Abstraction helps in chunking the information into utility


and underlying architecture.

12/15/2023 73
Abstraction

 One may look into the utility part of a module and


completely ignore the underlying structure of it

 Whereas someone interested in the underlying part do not


necessarily need to understand what is the utility or how
interaction if performed with the user (for example)

 Thus Abstraction helps in reducing the semantic load of


the information.

12/15/2023 74
Recap: Object and Class structure

 Object structure: Illustrates how different objects collaborate


with one another through patterns of interaction that we call
mechanisms

 Class structure: Highlights common structure and


behaviour within a system.

 Decomposition – Hierarchy – Abstraction

 These three are the main tool to use when we try to design a
complex system

 These three would be frequently used when we learn about


other concepts of OOAD.

12/15/2023 75
What we mean by “Design”?

 We would be using various types of Design approach in


OOAD and they would be applied on variety of problems

 Design would always refer to

 Something that satisfies a given functional specification

 Helps in addressing the limitation of the target system

 Meets the requirements on performance and resource of the target


system

 Satisfies restrictions on the design process such as constraints in


duration, cost, tools, etc.

12/15/2023 76
Evolution of Programming Languages

 First-generation (1954-1958)
 One global data and subprograms
 Error in one part effects rest of the system

 Second-generation (1959-1961)
 One global data and subprograms. Subprograms have individual modules
 Fails in programming-in-large scenario and design

 Third-generation (1962-1970)
 Structured, Modular, Abstraction
 Modules were separately compiled and hence no track of errors

 Fourth-generation (1970-1980)
 Large data handling with Database management

12/15/2023 77
Evolution of Programming Languages

 Object-orientation (1980-1990)
 Object-based models
 Exception handling
 Task-specific

 Emergence of Frameworks (1990-today)


 Programming frameworks
 Used for OOAD for large-scale systems
 Portable. Threading.
 Frameworks:
 J2SE, J2EE, J2ME
 .Net

12/15/2023 78
Foundations of Object Models

 OOAD is an Evolutionary development

 The approach is to start small/elementary and proceed to


develop the overall system

 Therefore a simpler to further complex in an iterative


manner is the process of Evolution in this context

 Following have contributed in this evolution:


 Computer architecture
 Programming language
 Programming methodology
 Database models
 Artificial Intelligence
 Philosophy and cognitive-science.

12/15/2023 79
Unified Modelling Language (UML)

12/15/2023 80
UML History
Unified Modeling Language (UML)
Unified Modeling Language

• General purpose modelling language

• Aim is to define standard way to visualize

• How a system is developed


• How the system would perform
• Who are the stakeholders of the system
• What would be the interactions between the
stackholders
• Etc.
UML is for Visual Modeling
Three (3) basic BUILDING blocks of UML
Relationships between Objects/Entities at
some point
Object Diagrams

More formally in UML


Model types

• Functional model: What are the functions


of the system?

• Object model: What is the structure of the


system? What are the objects and how are
they related?

• Dynamic model: How does the system


react to external events? How does the
events flow in the system ?
UML Basic Notation Summary

 UML provides a wide variety of notations for modeling many


aspects of software systems

 Example diagrams with respect to the different Models in UML:

 Functional model: Use case diagram

 Object model: Class diagram

 Dynamic model: Sequence diagrams, state chart


Unified Modeling Language (UML) - Diagrams
Unified Modeling Language (UML) - Diagrams
UML Core Conventions

• All UML Diagrams denote graphs of nodes and edges

• Nodes are entities and drawn as rectangles or ovals


• Rectangles denote classes or instances
• Ovals denote functions

• Names of Classes are not underlined


• SimpleWatch
• Firefighter

• Names of Instances are underlined


• myWatch:SimpleWatch
• Joe:Firefighter

• An edge between two nodes denotes a relationship between the


corresponding entities

92
What is a Use Case?

 Created by Ivar Jacobson (1992)

 “A use case is a sequence of transactions in a system


whose task is to yield a measurable value to an individual
actor of the system”

 Describes WHAT the system (as a “Black Box”) does


from a user’s (actor) perspective

 The Use Case Model is NOT an inherently object


oriented modeling technique.

93
Benefits of Use Cases

 Captures operational requirements from user’s perspective

 Gives a clear and consistent description of what the system


should do

 A basis for performing system tests

 Provides the ability to trace functional requirements into


actual classes and operations in the system

94
UML Use Case Diagrams

 A Use Case model is described in UML (Unified Modeling


Language) as one or more Use Case Diagrams (UCDs)

 A UCD has 4 major elements:

 The system described


 The actors that the system interacts with
 The use-cases, or services, that the system knows how to
perform
 The relationships between the above elements.

95
UML first pass: Use case diagrams
Classifier
Use Case

Actor.

System boundary

Use case diagrams represent the functionality of the system


from user’s point of view. Use cases are the tasks that a user would perform.
Historical Remark: UML 1 used packages

Package Use case


Watch

Actor
ReadTime

SetTime
WatchUser WatchRepairPerson

ChangeBattery

Use case diagrams represent the functionality of the system


from user’s point of view
System

 As part of use-case modeling, the boundaries of the


system developed must be defined

 Defining the boundaries of the system is not trivial

 Which tasks are automated and which are manual?

 Which tasks are performed by other systems?


 The entire solution that we supply should be
included in the system boundaries
 Incremental releases

98
System (cont.)

 A system in a UCD is represented as a box


 The name of the system appears above or inside the box

Traffic Violations Report System

99
Actor

 Someone or something that interacts with the system


(exchanges information with the system)

 An actor represents a role played with respect to the


system, not an individual user of the system

 Example:
 Policeman – Enters data

 Supervisor – Allowed to modify/erase data

 Manager – Allowed to view statistics

 A single actor may play more than one role.

100
Actor (cont.)

 Actors have goals:


 Add a Traffic Violation

 Lookup a Traffic Violation

 Actors don’t need to be human


 May be an external system that interfaces with the
developed system

 An actor has a name that reflects its role.

101
Actor Icons

 An actor models an external entity which


communicates with the system:
 User

 External system

 Physical environment

Passenger
 An actor has a unique name and an
optional description

 Examples:
 Passenger: A person in the train
 GPS satellite: Provides the system with
GPS coordinates
Use Case

 A use case achieves a goal of


value to an actor

 System does these things for


actors

 Describes what system is for?


And Not about how it does it

 Starts with an active verb from


the point of view of the system
Communications

 Lines between Actor and Use Case summarize interactions


graphically

 Actors and use cases exchange information to achieve the


goal but the details of interaction are not shown
UML first pass: Use case diagrams
Classifier
Use Case

Actor.

System boundary

Use case diagrams represent the functionality of the system


from user’s point of view. Use cases are the tasks that a user would perform.
UML first pass: Use case diagrams

Package Use case


Watch

Actor
ReadTime

SetTime
WatchUser WatchRepairPerson

ChangeBattery

Use case diagrams represent the functionality of the system


from user’s point of view
Diagrams in UML – Actors in Use case

• There is no standard available to


choose Actors for a system

• Selection of Actors and Use cases of a


system solely depends upon the
development team.
Diagrams in UML
Diagrams in UML – Actors in Use case
Diagrams in UML – Use cases in Use case diagram
Diagrams in UML – Use case Diagram
OOA – OOD - OOP

 Object Oriented Analysis (OOA)

 Object Oriented Design (OOD)

 Object Oriented Programming (OOP)

 Interrelation between OOA, OOD, and OOP

12/15/2023 112
Object Oriented Analysis (OOA)

 Object Oriented Analysis (OOA) is a method of analysis that


examines requirements from the perspective of the classes and
objects found in the vocabulary of the problem domain.

12/15/2023 113
Object Oriented Analysis (OOA)

 Stages for Object Oriented Analysis (OOA)

 Identifying Objects

 Identifying Structure

 Identifying Attributes

 Identifying Associations

 Defining services

12/15/2023 114
Object Oriented Design (OOD)

 It follows the Object Oriented Decomposition approach

 Three stages in the designing process

 Logical models (class and object structure)

 Physical models (module and process architecture)

 Behavioral models (statics and dynamics of the system)

12/15/2023 115
Object Oriented Design (OOD)

 Stages for Object Oriented Design (OOD)

 Defining the context of the system


 Usability of the system
 Number of users

 Designing system architecture


 Dependencies / associations between components
 Centralized / Decentralized ?
 Database schema required

 Identification of objects in the system


 Entities involved

 Construction of design models


 Types of models used for designing the system

 Specification of object interfaces


 Depends upon the objects and architecture of the system.

12/15/2023 116
Object Oriented Design (OOD)

 Object design includes the following phases (broadly)

 Identify the objects

 Representation of the objects (design models)

 Classification of operations
 Who is going to use?
 What are the restrictions?

 Algorithm design
 At what point during the design phase we should think about the algorithm
which would be running in the system?

 Association and Relationship among entities

 Identifying the external interactions and including them in the design


process

 Package classes and associations into modules.

12/15/2023 117
Object Oriented Programming (OOP)

 Analysis is the extraction of objects from the concepts and notions

 Analysis gives us certain set of objects and their inherent


properties

 Analysis also gives us how an object performs (theoretically)

 What messages need to be sent or received by the objects are also


included in the analysis phase

 OOD gives us the opportunity to put the concepts learnt from OOA
into the system

 OOD deals with the system architecture and ways in which the
observations from OOA can be induced into the system

 OOD also deals with handling the limitations of the system while
inducing the observations from OOA.

12/15/2023 118
Object Oriented Programming (OOP)

 Now using the inputs from OOA and OOD subsequently we need to
build the real-life system

 The real-life system would be the final finished product

 We need programming languages for implementation and a


successful running of the designed system

 Choosing the programming language for the designed system is


very important .. It depends upon specification and requirements
in the design.. And also on the features of the programming
language

 If we observe that the developed application needs to be moved


across different platforms (system and server configuration).. Then
one may use Python/Java which is very portable.

12/15/2023 119
Object Oriented Programming (OOP)
 On the other hand, Python is extremely slow in processing

 Therefore if there is a time constraint or processing power


constraint then we may choose a programming language which can
be executed very fast (C/C++)

 Choice of programming language selection would depend on how


the analysis is being done and how the system components are
designed

 Choice of OOP language does not depend upon popularity of


the language

 It depends upon
 What we need to do

 What are the constraints in the system we are developing

 What are the features of the chosen OOP language.

12/15/2023 120
Object Oriented Programming (OOP)
 On the other hand, Python is extremely slow in processing

 Therefore if there is a time constraint or processing power


constraint then we may choose a programming language which can
be executed very fast (C/C++)

 Choice of programming language selection would depend on how


the analysis is being done and how the system components are
designed

 Choice of OOP language does not depend upon popularity of the


language

 It depends upon
 What we need to do
 What are the constraints in the system we are developing
 What are the features of the chosen OOP language

 OOP is a programming language model organized around objects


rather than actions and data.

12/15/2023 121
Object Oriented Programming (OOP)
 Re-usability
 Reusing some facilities rather than building them again and
again

 It is achieved by using Class concept

 Any number of times we can use the contents of a class using


entities such as Objects

 Data redundancy

 Same piece of data is held in two separate places

 If a user wants a similar functionality in multiple classes

 Then we can write common class definitions for similar


functionalities and inherit them

12/15/2023 122
Object Oriented Programming (OOP)
 Code maintenance

 Maintenance of software includes fixing of bugs, improving the


code quality, etc.

 A well structured code where Object oriented concepts are


properly applied is easier to be maintained by developers

 Even very helpful to new employee who is "inheriting" the existing


project as time passes

 Security

 Object oriented concepts such as Abstraction help in hiding data

 Developers have option to conditionally expose data to externals.

12/15/2023 123
Object Oriented Programming (OOP)
 Design benefits

 The design benefits are in terms of designing, fixing things easily


and eliminating risks

 Developers have the option to create a better design of the


software with fewer flaws

 Better productivity

 Using the above features the final product is improved

 More features are included. Final product is easier to read,


use, and maintain

 Programmer can easily add new features to existing product.

12/15/2023 124
Class - Object
 Abstraction hierarchy gives Class structure
 How many classes?
 How many objects?
 Object of which classes?
 Why we create object of those classes?

 Vehicle->[4whl, 3whl, 2whl]->[Car, Truck, Bus]->[Sedan, SUV,


HatchBack]->[Tigor, Nexon, Tiago]

 Why Tiago would have all property of Cars?


 Why would we reveal all property of Cars to Tiago?
 Tiago should have property of Hatchback and nothing else
 Tiago should not know task of Tigor
 Tiago would know property that are specific to Hatchback
and not the inherit properties from Car class
 We can do specific changes to Tiago without changing
property of Tigor (modularity)

12/15/2023 125
Object Oriented Programming (OOP)
 Three important parts of OOP

 Object

 Class [Type]

 Inheritance

Data

12/15/2023 126
Class
 Objects have an associated Type which is known as the
Class

12/15/2023 127
Class – Objects – Methods
 Object oriented programs deal with Objects

 Objects are certain entities or modules

 That have certain behavior

 Their behavior may change as per requirement

 They hold information used within the program

 They can interact with one another.

12/15/2023 128
Class – Objects – Methods
 Here we write codes in separate blocks

 Each block is designed to perform separate tasks

 Such blocks are called the Classes

 Classes are the building blocks of OOP concept

 Each block/class stores information within


multiple methods

 Methods within classes are used to perform sub-


tasks.

12/15/2023 129
Class – Objects – Methods
Method -1 Method -1 Method -1
Method - 2 Method – 2
Method - 3
Class 1 Class 2
Class 3

 Objects are the instance of a class or executable copy of the class

 Multiple objects might exist for a class

 Each object can perform separate tasks.

12/15/2023 130
Class
 Class is a structure that defines the data and
methods to work on

 Each class has a well-defined responsibility

 The responsibility of a Class is on a higher level

 It consists of instance variables and methods

 It provides modularity and structure in an object-


oriented computer program.

12/15/2023 131
Methods
 Class consists of collection of methods

 Methods define specific sub-tasks that are


assigned for a class

 Communication between classes are performed


using methods

 Methods within a class is accessed using Objects.

12/15/2023 132
Objects
 Objects are instances of a class or an executable
copy of a class

 There can be multiple objects of a class

12/15/2023 133
First program
class test
{
public static void main (String args[ ])
{
System.out.println (“Hello World!!”);
}
}

 class test
 Declares a class named as test
 Contains a single method “main( )”
 “class” is a keyword
 “test” is the identifier which provides name to the new class.

12/15/2023 134
First program
 public static void main(String args[ ])

 public
 It is an Access specifier
 It is used to declare the method main( ) as unprotected
 Makes it accessible to all other classes

 static
 Every method is accessed using the object of a particular class
 Static method can be accessed directly without using objects
 main( ) should be declared static as it is the first method from which
execution starts
 Object creation for the main( ) method container class is not possible
prior to execution

 void
 main( ) do not return any value

 String args[ ]
 Handling command line arguments.

12/15/2023 135
First program
class sample
{
void display( )
{
System.out.println(“Pramit”);
}
}
class test
{
public static void main(String args[])
{
sample SS = new sample( );
SS.display( );
}
}
12/15/2023 136
Object creation
sample SS;

SS = new sample( );

 sample SS
 Reference created
 Storage space taken
 Storage space not yet instantiated

 SS = new sample( )
 Storage space instantiated
 Sample class object created.

 Multiple objects can be created to access the same


method of a class.

12/15/2023 137
Inheritance
 Types [classes] may inherit attributes from supertypes
[superclasses]

12/15/2023 138
How are OOA, OOD, and OOP related?
 OOA is concerned with developing an object model that capture the
requirements

 OOD is concerned with translating OOA model into a specific model that
can be implemented by a software

 OOP is concerned with realizing the OOD model using OOP language such
as Java, C++, etc.

12/15/2023 139
Important Topics

 Understand the major elements / essential


characteristics of Object Models

 Understand Abstraction

 Understand Encapsulation

12/15/2023 140
Elements of Object Models

 Four major elements of the Object Model

 Abstraction

 Encapsulation

 Modularity

 Hierarchy

12/15/2023 141
Elements of Object Models

 Three minor elements of the Object Model (useful


but not essential)

 Typing

 Concurrency

 Persistence

12/15/2023 142
Abstraction

 Abstraction is the simplifying a problem by


omitting unnecessary details

 Popularly known as the Model Building

 Example:

 Press the Break to control the Car

 One knows how to control a Car by pressing Breaks

 Without knowing how it works !

12/15/2023 143
Abstraction

Two observers look at the two views of the same object.

12/15/2023 144
Abstraction

 You are asked to develop an overall understanding


of the India

 What would be your approach:


 Meet all citizens of India?
 Visit every house?

 You would possibly only refer to various types of Maps


for explaining India.

12/15/2023 145
Abstraction

 Political Map: Administrative structure

 Rivers Map: Natural distribution for water

 Power-Grid Map: Power distribution profile

 Vegetation Map: Cultivation pattern

 Railways Map: Spread of Connectivity

 World Heritage Site Map: Cultural heritage.

12/15/2023 146
Abstraction
 Example
 Class-1 is having 10 properties
 Object-1 is created for Class-1
 Object-1 would have all 10 properties
 Now You want to allow User-1 to access the system using
Object-1
 Also you want User-1 not to access property 5-10 which are
there in Class-1
 You create Class-2 and pass property 5-10 of Class-1 to
Class-2
 Thus make Class-2 as generalized class for Class-1
(Inheritance)
 Thus User-1 using Object-1 of Class-1 gets to use all
properties without visualizing the working of properties 5-10
which are not written in Class-1.

12/15/2023 147
Abstraction

 Several abstractions of the same problem are


possible:
 Each abstraction deals with a specific problem
 Focus on some specific aspect and ignore the rest
 Use different models for different aspects of the problem

 For complex problems


 A single level of abstraction is inadequate
 Single level does not simplify the system
 A hierarchy of abstraction needs to be constructed
(Abstraction Hierarchy)

 Hierarchy of models
 A model in a layer is abstraction of the lower layer of
models
 Higher layer models implement the model in the layer.

12/15/2023 148
Abstraction Hierarchy: Living Organisms

More deeper level of hierarchy can be achieved

12/15/2023 149
Abstraction Hierarchy: LMS

12/15/2023 150
Abstraction
 Executive, Lead, and Manager are a type of Employee

 Thus they have a IS-A relationship with Employee

 Characteristics common to Executive/ Lead/ Manager are


mentioned in Employee

 Example: Name, ID, DoB are common to all Employees of an


organization (Executive, Lead, Manager)

 Lower hierarchy abstractions can have their own set of


characteristics
 Reporting_Lead for Executive abstraction
 Reporting_Manager for Lead abstraction
 List of Reporting Leads for Manager abstraction

12/15/2023 151
Abstraction
 All lower level abstraction in the hierarchical structure are
known as the Specialization

 Example: Executive is a specialization of Employee

 Whereas, Employee is the generalization of Executive, Lead,


and Manager

 A generalized abstraction contains all the common


characteristics of its specialization

 Specialization in turn can be certain specific characteristics


which is not present in the generalized abstraction.

12/15/2023 152
Abstraction
 Example:
 Generalized “Employee” have 4 responsibilities which are
common for Executive, Lead, and Manager

 Specialization “Executive” have 1 responsibility which is specific


to the abstraction

 Specialization “Lead” have 5 responsibilities which are specific to


the abstraction

 Specialization “Manager” have 4 responsibilities which are


specific to the abstraction

12/15/2023 153
Abstraction Hierarchy: LMS

12/15/2023 154
Abstraction
 More commonalities can be observed

 “Lead” approve Leave request from “Executive”

 “Lead” regret Leave request from “Executive”

 “Lead” revoke Leave request from “Executive”

 “Manager” approve Leave request from “Lead”

 “Manager” regret Leave request from “Lead”

 “Manager” revoke Leave request from “Lead”

Commonalities ??
Approve Approve
Executive Regret Lead Regret Manager
Revoke Revoke

12/15/2023 155
Abstraction

LMS

Executive Approve Regret Revoke

Lead Manager

Addition of a new concept in terms of a new abstraction hierarchy.


Abstractions are better understood when put into hierarchy.

12/15/2023 156
Multi Level Hierarchy

obtained from Sensor


obtained from Temperature Sensor

12/15/2023 157
Elements of Object Models
 Four major elements of the Object Model

 Abstraction

 Encapsulation

 Modularity

 Hierarchy

 Three minor elements of the Object Model (useful but not


essential)

 Typing

 Concurrency

 Persistence

12/15/2023 158
Encapsulation
 Primary task is to encapsulate

 The task is to put everything into one envelope

 By the term envelope we mean putting many different things


together into a single box/module

 This strategy helps other developers to use it through a well


planned approach

 It helps the elements of an abstraction to be grouped on


basis of two aspects
 Structure / characteristics / properties / variables
 Behavior / responsibilities / tasks / methods

12/15/2023 159
Encapsulation: Example

12/15/2023 160
Encapsulation: Example

12/15/2023 161
Encapsulation: Example
 Structure is encapsulated in the implementation
 Store for the elements
 static or dynamic array
 Single linked list
 Deque
 Marker for the top element
 Array index
 List pointer
 Encapsulated in Deque
 Hidden from the external world

 Behavior is exposed through interface


 Interface for a stack
 Push
 Pop
 Top
 Empty
 Exposed to the external world

12/15/2023 162
Encapsulation
 For an Abstraction, the Encapsulation concept separates

 Contractual Interface / Behaviors (Push – Pop – Top - Empty)

 Implementation (Array - List - Deque)

 Encapsulation binds together the data and functions that


manipulate the data

 Encapsulation keeps both (data and function) safe from the


outside interference and misuse

 Data Abstraction => Data Hiding

 “Encapsulation” concept helps to perform “Abstraction”


while Implementing a software.

12/15/2023 163
Encapsulation
 Remember that Encapsulation or hiding of the complex
concepts are important

 For example a user would not care to understand the


mechanism about how an ATM dispenses cash

 However, if everything is encapsulated then the system


cannot be used

 Therefore, developing an interface for the user to interact


and understand the basic working principle is important

 Thus both “Contractual Interface” (abstract) and


“Implementation” (implement) are important.

12/15/2023 164
Encapsulation
 So the concept is similar to Client-Server model where
Interface is what the Client gets to see and Server is the
implementation details which remains encapsulated

 Interface provided to the Client always remains consistent


with the underlying implementation

 For example: Buttons used for push/pop, etc. operation


remains same

 Whereas, the procedure or code used to perform the


push/pop operation might change

 Such change can be done in the server end or the


implementation end which is encapsulated or hidden from
the user/ client.
12/15/2023 165
Why the name “Contractual”?
 “Contractual” in the sense that we would confirm a set of
operations that the user can perform in our software

 So that user gets an assurance for the set of tasks that it


can perform. Discrete Systems !!

 Of course we can change the interface, but the basic


working or tasks which needs to be performed by the user
should be not be changed much

 We can always modify the server part- which is hidden


from the user (how the system worked)

 Thus we say that the interface is kind of “Contracted” to


perform certain fixed set of tasks.

12/15/2023 166
Encapsulation: Example

 Structure = part of Implementation, and are Hidden

 Behavior = part of Interface, and are public anyone can use


without understanding how “cancellation” is performed.

12/15/2023 167
Abstraction Hierarchy: LMS

12/15/2023 168
Abstraction vs Encapsulation
Abstraction Encapsulation
Solves the problem in the design level Solves the problem in the
implementation level
Hide the unwanted data and expose Hide the code and data into a single
useful data unit to protect the data from outside
world
Allows us to focus on what the object Hide the internal details or mechanics
does instead of how it does it of how an object does something
Provides outer layout, in terms of Provides inner layout used in terms of
design outer
Example: Look of a Mobile phone has Example: Implementation detail of a
a display screen and keypad buttons mobile phone deals with how keypad
to dial a number. button and display screen connect with
each other.

12/15/2023 169
Elements of Object Models
 Four major elements of the Object Model

 Abstraction

 Encapsulation

 Modularity

 Hierarchy

 Three minor elements of the Object Model (useful but not


essential)

 Typing

 Concurrency

 Persistence

12/15/2023 170
Modularity
 Modularity depicts how the code and data are organized

 Modularity is to partition a program into individual


components

 Modularity is done to manage complexity (reduce


complexity)

 Module characteristics

 Compile separately or together

 Connected with the other modules

12/15/2023 171
Modularity: Example

12/15/2023 172
Modularity: Example

12/15/2023 173
Modularity: Example

12/15/2023 174
Modularity: Example

12/15/2023 175
Modularity: Example

12/15/2023 176
Modularity: Example

12/15/2023 177
Modularity: Example

12/15/2023 178
Modularity: Example
 Modularity ensures

 Partitioning the program codes into interrelated set of files and


data

 Also maintain the interconnections between the partitioned


program codes

 For example: the below sub-components performs the task of


interconnection between the modules.

12/15/2023 179
Modularity
 It is always easier to look into the system when modularized

 It is easier to divide the tasks when modularization is


assured

 There can be hierarchy in a modularized structure.

12/15/2023 180
Modularity: Objectives
 Modular Decomposition

 Systematic mechanism to divide problem into individual


components

 We only put together a set of code into one module which have
some sort of well-defined functionality

 So that together they represent a certain functionality/ concept

 Modular Composability
 Modularization should be done in such a way that we can
reconstruct it back

 Combine smaller modules into a bigger module if required

 Enables reuse of existing components.

12/15/2023 181
Modularity: Objectives
 Modular Understandability

 Understand each module as a unit

 Example: For performing i/o operation lets include stdio.h !!

 Here we do not know what is the underlying structure of stdio.h,


but what we know is a concept that for i/o related operations we
need to include all functions within stdio.h .. This is
understandability.

12/15/2023 182
Modularity: Objectives
 Modular Continuity

 We need to make the modules in such a way that it is easier to


make changes

 Example: Bug fixation, Change in specification, Change in


Business, etc.

 So we should not end-up in a situation where for one change, we


need to modify multiple module (i.e. change across modules)

 Change should be limited to one module or at least a smaller


number of modules

 Thus it reduces side-effects.

12/15/2023 183
Modularity: Objectives
 Modular Protection

 Errors should be localized

 If there is an error “divide by zero” then that should be localized


to math.h

 If there is an error “memory allocation failure” then that should


be localized to memory.h and so on

 Errors should not spread across multiple modules.

12/15/2023 184
Modularity: Challenges
 Decomposition into smaller module may be difficult

 Arbitrary modularization is sometimes worse than no


modularization

 Modularization should follow the semantic grouping of


common and interrelated functionality of the system.

12/15/2023 185
Modularity: Example
 Consider a Distributed System
 Runs on a distributed set of processors
 Uses a message passing mechanism to coordinate the activities of
different programs
 Has several hundreds of event & few thousand kinds of messages

 What should be the strategy to modularize?


 Naïve strategy might be to define each message class in own
module
 This strategy is poor because it would end up into numerous
modules
 Documenting the system would be a nightmare !!
 Difficult to find classes
 When decisions change, updating hundreds of modules are
required
 Thus hiding information becomes a problem.

12/15/2023 186
Intelligent Modularization
 Group logically related abstraction

 Minimize dependency among modules

 Simple enough to understand fully

 Ease of change
 Possibility to change the implementation strategy of an individual module

 Without enough knowledge of other modules

 Without effecting the working of other modules

 Change in a module for an already implemented system needs reasonable


justification of the benefits for the change.

12/15/2023 187
Elements of Object Models
 Four major elements of the Object Model

 Abstraction

 Encapsulation

 Modularity

 Hierarchy

 Three minor elements of the Object Model (useful but not


essential)

 Typing

 Concurrency

 Persistence

12/15/2023 188
Hierarchy
 Hierarchy is a ranking or ordering of abstractions

 The set of abstraction that a system have moves from “less


details” to “more details”

 The bottom-most level have highest level of details, and top-


most level have the minimal details

12/15/2023 189
Hierarchy
 Two most important hierarchies in a complex system are
 Class structure or is-a hierarchy (Abstraction or IS-A)

 Object structure or part-of hierarchy (Decomposition or HAS-A)

 Common structure and behavior are migrated to superclass


 Superclass represent generalized abstraction

 Subclass represent specializations

 Subclass can add, modify and hide methods from superclass

12/15/2023 190
Hierarchy
 Hierarchy provides an opaque barrier to hide the methods
and state

 Inheritance is required to open this interface and allow state


and methods to be accessed between two levels of
abstraction

 Different programming languages trade-off support for


inheritance in different ways

 C++ and Java offer great flexibility

 Private variables/modules – accessible only to the class

 Protected variables/ modules – accessible only to the class and


its subclasses

 Public variables/ modules – accessible to all clients.

12/15/2023 191
Single Inheritance
 A single superclass is inherited by a single subclass

 Class B IS-A Class A

 Class B is the specialization of Class A

 Class A is the generalization of Class B

12/15/2023 192
Multi-level Inheritance

12/15/2023 193
Multiple Inheritance
 For certain abstractions, it is important to provide
inheritance from multiple superclasses

studies teaches

Student Teacher

studies +
teaches
Teaching Assistant
12/15/2023 194
Multiple Inheritance: Challenges
 A very critical and important concept related to Hierarchy

 It is easy to identify the multiple inheritances (or where we


need multiple inheritances)

 But there are a lot of fundamental, theoretical and


conceptual factors which one need to look into while dealing
with multiple inheritance

 For example if we inherit the same method from two


different superclasses, then what would be the behavior of
the method in the sub-class.

12/15/2023 195
Hierarchical Inheritance
 More than one sub classes are created from the same super
class

12/15/2023 196
Hybrid Inheritance
 It may be a combination of

 Multilevel and Multiple inheritance

 Hierarchical and Multilevel inheritance

 Hierarchical and Multiple inheritance

12/15/2023 197
Single Inheritance - Example
class one public class Single_Inheritance
{ {
int x; public static void main(String[] args)
public void print_1( ) {
{ two g = new two( );
x = 10; g.print_1( );
System.out.println("CSE"); g.print_2( );
}
System.out.print(g.x);
}
}
class two extends one
{ }
public void print_2( )
{ OUTPUT:
System.out.println("IIIT Vadodara"); CSE
} IIIT Vadodara
} 10

12/15/2023 198
Single Inheritance – Class Diagram

One
+ x: int
+ print_1( )
Single_Inheritance

+ main( ): void
Two

+ print_2( )

12/15/2023 199
Multilevel Inheritance
 A child class derives member variables
and methods from another derived
class.

A: Parent class

B: Child class

C: Child class

12/15/2023 200
Multilevel Inheritance - Example
class X class Z extends Y {
{ int k;
int i; Z( ) {
X( ) k=9; j++;
{ }
i=5; }
} public class Multilevel_Inheritance{
} public static void main(String args[]) {
class Y extends X X a = new X();
{ Y b = new Y();
int j; Z c = new Z();
Y( ) System.out.println(a.i);
{ System.out.println(b.i + b.j);
j=7; i++; System.out.println(c.i + c.k);
} System.out.println(c.i + c.j + c.k);
} } }

12/15/2023 201
Multilevel Inheritance – Class Diagram
X
+ i: int
+ X( )

Multilevel_Inheritance
Y
<<create>>
+ j: int
+ Y( ) + main( ): void

Z
+ k: int
+ Z( )

12/15/2023 202
Hierarchical Inheritance
 One base class is derived by many child
classes.

A: Parent class

B: Child class C: Child class

12/15/2023 203
Hierarchical Inheritance - Example
class Shape class rectangle extends Shape {
{ int k;
int i; rectangle( )
Shape( ) {
{ k=7;
i=5; }
} }
} class Hierarchical_Inheritance {
public static void main(String args[]) {
class square extends Shape Shape a = new Shape();
{ square b = new square();
int j; rectangle c = new rectangle();
square( ) System.out.println(a.i);
{ System.out.println(b.i * b.j);
j=6; System.out.println(c.i + c.k);
} } } }

12/15/2023 204
Hierarchical Inheritance – Class Diagram
Shape
+ i: int
+ Shape( )

square rectangle
+ j: int + k: int
+ square( ) + rectangle( )

Hierarchical_Inheritance

+ main( ): void

12/15/2023 205
Constructors
class Shape class rectangle extends Shape {
{ int k;
int i; rectangle( )
Shape( ) {
{ k=7;
i=5; }
} }
} class Hierarchical_Inheritance {
public static void main(String args[]) {
class square extends Shape Shape a = new Shape();
{ square b = new square();
int j; rectangle c = new rectangle();
square( ) System.out.println(a.i);
{ System.out.println(b.i * b.j);
j=6; System.out.println(c.i + c.k);
} } } }

12/15/2023 206
Constructors
 It is a method which gets initialized at the time of object
creation

 New keyword used to instantiate an object also initializes the


constructors

 Do not need objects to call them

 They have same name as that of the containing Class

 Multiple constructors may exist in a single Class

 Multiple constructors should have different parameter list.

2013: J Paul Gibson


Constructors
 They do not have a return type

 They returns instance of the class i.e. the new object

 If a class is not having a constructor,

 Java creates a default constructor

 Default constructor with no parameters sets all fields to zero

 Any variable declared within a constructor is Local to the


constructor

 No other constructor can access a variable local to another


constructor.

2013: J Paul Gibson


Constructor example
public class Point {
int x;
int y;

public Point(int initialX, int initialY) {


x = initialX;
y = initialY;
}

public void translate(int dx, int dy) {


x = x + dx;
y = y + dy;
}

...
}
Tracing a constructor call
 What happens when the following call is made?

Point p1 = new Point(7, 2);


p1.translate(5, 10);

p1 x y

public Point(int initialX, int initialY) {


x = initialX;
y = initialY;
}

public void translate(int dx, int dy) {


x = x + dx;
y = y + dy;
}
Common constructor bugs
1. Re-declaring fields as local variables ("shadowing"):

public Point(int initialX, int initialY) {


int x = initialX;
int y = initialY;
}

 This declares local variables with the same name as the fields,
rather than storing values into the existing variables. The existing
attributes remain 0.

2. Accidentally giving the constructor a return type:

public void Point(int initialX, int initialY) {


x = initialX;
y = initialY;
}

 This is actually not a constructor, but a method named Point


Constructor example
public class Point {
int x;
int y;

public Point(int initialX, int initialY) {


x = initialX;
y = initialY;
}

public void translate(int dx, int dy) {


x = x + dx;
y = y + dy;
}

...
}
Constructor example
public class PointMain3 {
public static void main(String[] args) {
// create two Point objects
Point p1 = new Point(5, 2);
Point p2 = new Point(4, 3);

// print each point


System.out.println("p1: (" + p1.x + ", " + p1.y + ")");
System.out.println("p2: (" + p2.x + ", " + p2.y + ")");

// move p2 and then print it again


p2.translate(2, 4);

// print each point once again


System.out.println("p1: (" + p1.x + ", " + p1.y + ")");
System.out.println("p2: (" + p2.x + ", " + p2.y + ")");

} }
Multiple constructors
 A class can have multiple constructors.
 Each one must accept a unique set of parameters.

 Exercise: Write a Point constructor with no parameters


that initializes the point to (0, 0).

// Constructs a new point at (0, 0).


public Point() {
x = 0;
y = 0;
}
Constructor example
public class Point {
int x; int y;

public Point() {
x = 0;
y = 0;
}
public Point(int initialX, int initialY) {
x = initialX;
y = initialY;
}

public void translate(int dx, int dy) {


x = x + dx;
y = y + dy;
}
}
Constructor example
public class PointMain3 {
public static void main(String[] args) {
Point p1 = new Point(5, 2);
Point p2 = new Point(4, 3);
Point p3 = new Point();

// print each point


System.out.println("p1: (" + p1.x + ", " + p1.y + ")");
System.out.println("p2: (" + p2.x + ", " + p2.y + ")");
System.out.println("p3: (" + p3.x + ", " + p3.y + ")");

p2.translate(2, 4);
System.out.println("p2: (" + p2.x + ", " + p2.y + ")");
}
}
Types of Constructors
 Parameterized Constructor

 Non parameterized constructors

 Default constructors

 Copy constructors

 Constructor overloading
Copy Constructor
 A copy constructor is a method/constructor that
initialize an object using another object within the
same class

 Enables to get a copy of an existing object

 Copy constructors take only one parameter

 The parameter is a reference of the same class.


Copy Constructor
 Advantages of using copy constructors:

 Copying an object with multiple attributes

 when you have a complex object with many attributes it is much simpler
to use the copy constructor

 if you add an attribute to your class, you just change the copy
constructor to take this new attribute into account instead of changing
every occurrence of the other constructor.

 Copying the constructors can be performed by:

 Shallow copy

 Deep copy
Copy Constructor
 Shallow copy

 Creates a copy of an object by copying data of all member


variables as it is

 Point p1 = new Point(5,9);


 Point p2 = p1; //copy

 Objects p1 and p2 are referencing to the same memory location

 Changes made in one object will effect the other

 What if we want to Copy but create a separate entity?


Copy Constructor
 Deep copy

 Dynamically allocates memory for the new object

 Copies existing entities of the existing object

 Entities of the existing object is duplicated to the new object

 Both objects are located at different memory locations

 There is no connection between the two object

 Subsequent changes made to one does not affect the other

 Also known as user-defined copy constructor.


Elements of Object Models
 Four major elements of the Object Model

 Abstraction

 Encapsulation

 Modularity

 Hierarchy

 Three minor elements of the Object Model (useful but not


essential)

 Typing

 Concurrency

 Persistence

12/15/2023 222
Minor Elements
 These are not essential elements

 Depending upon the skill of the designer

 Depending upon the Specification of the system to be


developed

 Such minor elements may be considered.

12/15/2023 223
Typing
 This is NOT the Word/Code typing speed !!

 Typing is the representation of the type of a class or type of an


object associated with a class

 It is important because
 Usually in programming we have variables
 Variable have a definite type or datatype
 We know what type of data we need to store and accordingly define the types
 However, for an object the scenario is different
 It is not going to have a single value
 It is going to represent a class
 Inherent properties of the class which the object refers to needs to be understood
 Inherent properties of the class which is being referred by an object is the Type of
the Object.

 Typing is the enforcement of the class of an object such that


objects of different types
 May not be interchanged
 May be interchanged only in very restricted ways

12/15/2023 224
Typing
 Type derives from the theory of abstract data types (ADT)

 ADT consists of

 Domain
 Range of values that can be stored

 Operations
 What operations can be performed with that value

 Axioms
 How the operations which can be performed, interplay among themselves

 Type is a precise characterization of structural or behavioral


properties which a collection of all entities will share

12/15/2023 225
Typing
 Built-in (Primitive) Types
 Int
 Double
 char
 bool

 User-defined Types (UDT)


 Complex
 Vector
 Employee
 Executive
 Leave
 CasualLeave

12/15/2023 226
Type of Programming Languages
 A programming language may be

 Statically typed – static binding or early binding [C]

 Types are associated with Variables not Values

 Variable has a type and it is defined while writing the programing

 Compiler know the type of the variable at compile-time

 Type of a variable always remains constant (check line 3-4)

 Static type checking is the process of verifying the type safety of a


program based on analysis of a program’s text

 Example: C, C++, Java, etc.

12/15/2023 227
Type of Programming Languages
 Dynamically typed – dynamic binding or late binding

 Types are associated with values not variables [Python]

 Type of a variable is associated with the type of value assigned


to it and not type of the variable

 Dynamic type checking is the process of verifying the type of


program at run-time

 Example: Python, (C++ and Java) via Polymorphism, etc.

12/15/2023 228
Type of Programming Languages
 Strongly Typed

 Typing errors are prevented at runtime

 Allow little implicit type conversion

 Does not use static type checking

 Compiler does not check or enforce type constraint

 Example: Python, C++, Java

 Weakly Typed

 Allow implicit type conversion

 Example: C, some features of C++ and Java

 Untyped

 There is no type checking and any type conversion reqd. is explicit

 Example: Assembly level language

12/15/2023 229
Polymorphism
 Polymorphism exists when dynamic typing and inheritance
interact

 A single name (such as variable) may denote multiple objects


of different classes that are related by some common
superclass

 dynamic typing:
 X = 2;
 X = 2.5;

 Polymorphism is a very important tool to perform


abstraction in an OOP.

12/15/2023 230
Signatures
Signatures
 In any programming language, a signature is what
distinguishes one function or method from another

 In C, every function has to have a different name

 In Java, two methods have to differ in their names or


in the number or types of their parameters
 foo(int i) and foo(int i, int j) are different

 foo(int i) and foo(double k) are different

 foo(int i, double d) and foo(double d, int i) are


different

 In C++, the signature also includes the return type


 But not in Java!
Polymorphism
 Polymorphism means many (poly) shapes (morph)

 In Java, polymorphism refers to the fact that you can


have multiple methods with the same name in the same
class

 A method in Java can behave in multiple ways, thus


performing different sub-tasks

 So the method posses different behavior at different


situations and a programmer can make use of this
feature.

233
Polymorphism
 This feature is known as Polymorphism

 It allows to perform same task in different ways

 Java performs polymorphism in two ways:

 Compile time polymorphism

 Run time polymorphism

234
Java Program Execution Steps

235
Polymorphism
 Compile time polymorphism (Static/Early binding)

 Function call to such method is resolved at compile time


 Performed by Method Overloading
 Also known as Static polymorphism

 Run time polymorphism (Dynamic method displatch)

 Performed by Method Overriding


 Function call to such method is resolved at runtime
 Replaces an inherited method with another having the same
signature.

236
Overloading
class Test {
public static void main(String args[]) {
void myPrint(5);
void myPrint(5.0);
}
static void myPrint(int i) {
System.out.println("int i = " + i);
}
static void myPrint(double d) { // same name, different parameters
System.out.println("double d = " + d);
}
}

int i = 5
double d = 5.0

237
Why overload a method?
 So you can use the same names for methods that do essentially the
same thing
 Example: println(int), println(double), println(boolean),
println(String), etc.

 So you can supply defaults for the parameters:


int increment(int amount) {
count = count + amount;
return count;
}
int increment() {
return increment(1);
}
 Notice that one method can call another of the same name

238
DRY (Don’t Repeat Yourself)
 When you overload a method with another, very similar
method, only one of them should do most of the work:

void dict_Example( ) {
System.out.println("first = " + first + ", last = " + last);
for (int i = first; i <= last; i++) {
System.out.print(dictionary[i] + " ");
}
System.out.println();
}

void dict_Example(String s) {
System.out.println("At checkpoint " + s + ":");
dict_Example();
}

239
Legal assignments
class Test {
public static void main(String args[]) {
double d;
int i;
d = 5; // legal
i = 3.5; // illegal
i = (int) 3.5; // legal
}
}

 Narrowing is legal
 Widening is illegal (unless you cast)

240
Legal method calls
class Test {
public static void main(String args[]) {
myPrint(5);
}
static void myPrint(double d) {
System.out.println(“Output: ” + d);
}
}
Output 5.0

 Legal because parameter transmission is


equivalent to assignment
 myPrint(5) is like double d = 5;
System.out.println(d);

241
Illegal method calls
class Test {
public static void main(String args[]) {
myPrint(5.2);
}
static void myPrint(int i) {
System.out.println(i);
}
}

myPrint(int) in Test cannot be applied to (double)

 Illegal because parameter transmission is equivalent to


assignment
 myPrint(5.2) is like int i = 5.2; System.out.println(i);

242
Method Overloading
 It is a technique in which a single class contains

 Multiple methods
 Of same name
 But different parameter list
 For distinguishing among themselves
 Object of the class is used to call each method.

class test{
void display() { }
void display(int x) { }
void display(int x, int y) { }
}
Constructor Overloading
 It is a technique in which a single class contains

 Multiple constructors
 Of same name
 But different parameter list
 For distinguishing among themselves
 Object of the class is not used to call the constructors.

class test{
test( ) { }
test(int x) { }
test(int x, int y) { }
}
Java uses the most specific method
class Test {
public static void main(String args[]) {
myPrint(5);
myPrint(5.0);
}
static void myPrint(double d) {
System.out.println("double: " + d);
}
static void myPrint(int i) {
System.out.println("int: " + i);
}
}

int: 5
double: 5.0
245
Operator Overloading
 Methods and Operators can be overloaded;
 Method overloading (includes constructors)
 Operator overloading

 Java does not support Operator Overloading

 C++ does support Operator Overloading along with


Method/Function overloading.
Operator Overloading
 Operators are overloaded to give user defined
meaning to it

 Examples: t1 / t2 or t1 == t2

 Overloaded operator is used to perform different


operations on variables

 Example: ‘+’ operator can be overloaded to


perform addition on various data types, like for
Integer, String concatenation, etc.

12/15/2023 247
Operator Overloading - Example

12/15/2023 248
Operator Overloading
 Almost all operators can be overloaded

 Few operators cannot be overloaded

 List of operators which cannot be overloaded are;


 scope operator - ::

 sizeof

 member selector - .

 member pointer selector - *

 ternary operator - ?:

12/15/2023 249
Operator Overloading - Syntax

12/15/2023 250
Operator Overloading - Restrictions
 Precedence and Associativity of an operator
cannot be changed.

 Arity (numbers of Operands) cannot be changed.


Unary operator remains unary, binary remains
binary etc.

 No new operators can be created, only existing


operators can be overloaded.

 Cannot redefine the meaning of a procedure. You


cannot change how integers are added.

12/15/2023 251
/ Operator Overloading - Example
class test void test::operator/(test t2)
{ {
int n; cout << n / t2.n;
public: }
test( )
{ int main( ) OUTPUT:
cin >> n; {
} test t1, t2;
10 <= t1.n
t1 / t2;
void operator/(test); 5 <= t2.n
return 0;
}; } 2

12/15/2023 252
<< Operator Overloading - Example
class test {
int n;
public:
test( ) {
cin>>n;
}
void operator/(test);
friend ostream& operator<< ( ostream&, test& );
};

void test::operator/(test t2) {


cout << n/t2.n;
}
12/15/2023 253
<< Operator Overloading - Example
ostream& operator<< ( ostream &out, test &t1 )
{
out << endl << "Value is " << t1.n;
return out;
}

int main( )
{
test t1,t2;
t1 / t2;
cout << t1;
return 0;
}
12/15/2023 254
== Operator Overloading - Example
class test {
int n;
public:
test( ) {
cin>>n;
}
void operator/(test);
friend bool operator== ( test, test );
};

void test::operator/(test t2) {


cout << n/t2.n;
}
12/15/2023 255
== Operator Overloading - Example
bool operator== ( test t1, test t2 )
{
return ( t1.n == t2.n );
}

int main( )
{
test t1,t2;
t1/t2;
cout << endl << ( t1 == t2 );
return 0;
}

12/15/2023 256
Multilevel Inheritance
 A child class derives member variables
and methods from another derived
class.

A: Parent class

B: Child class

C: Child class

12/15/2023 257
Method Overriding
 If subclass (child class) has the same method as
declared in the parent class, it is known as method
overriding

 If subclass provides specific implementation of the


method that has been provided by one of its parent
class, it is known as method overriding

 Advantage:
 Provide specific implementation of a method that is already provided by
its super class

 Rules:
 Same name as method in parent class
 Same parameter as in the parent class
 Must be in a IS-A relationship (inheritance)

12/15/2023 258
Method Overriding - Example
class Bank{ class AXIS extends Bank{
int getRateOfInterest( ) int getRateOfInterest( )
{ return 0; } { return 9; }
} }
public class Method_Overriding{
class SBI extends Bank{ psvm(S a[]){
int getRateOfInterest( )
{ return 8; } SBI s=new SBI( );
} ICICI i=new ICICI( );
AXIS a=new AXIS( );
class ICICI extends Bank{ S.O.P(“SBI”+ s.getRateOfInterest( ));
int getRateOfInterest( ) S.O.P(“ICICI”+i.getRateOfInterest());
{ return 7; } S.O.P(“AXIS”+a.getRateOfInterest());
}
}
}

12/15/2023 259
Method Overloading vs Overriding
Method Overloading Method Overriding

Used to increase readability of a Used to provide the specific


program implementation of the method that
is already provided by its super
class

Always performed within a class Occurs in two classes that have a


IS-A relationship

Parameters of two overloaded Two overridden methods should


methods should be different. have same parameters.

12/15/2023 260
Access Specifiers
 Types of Access Specifiers:

 Public

 Default (Friendly)

 Protected

 Private

12/15/2023 261
Access Specifiers or Visibility Modes
 Provides a restriction over the scope of a
variable/entity of a program

 Scope is applicable with respect to the following;

 Class

 Sub-class

 Package

 It is a group of similar types of classes, interfaces, etc.

12/15/2023 262
Public Access Specifier
 Public attributes/methods are accessible from
anywhere in the program

 All sub classes can access public members

 Classes in other packages can also access public


members.

12/15/2023 263
Protected Access Specifier
 WHO CAN ACCESS
1. All members within the same class
2. All members within sub-classes
3. Sub-classes present in the same package
4. Classes of same package which are not related
5. Sub-classes present in other packages.

 WHO CANNOT ACCESS


6. Classes in other packages, which are not sub-classes.

12/15/2023 264
Default (Friendly) Access Specifier
 WHO CAN ACCESS
1. All members within the same class
2. All members within sub-classes
3. Sub-classes present in the same package
4. Classes of same package which are not related.

 WHO CANNOT ACCESS


5. Sub-classes present in other packages
6. Classes in other packages, which are not sub-classes.

12/15/2023 265
Private Protected Access Specifier
 WHO CAN ACCESS
1. All members within the same class
2. All members within sub-classes
3. Sub-classes present in the same package
5. Sub-classes present in other packages

 WHO CANNOT ACCESS


4. Classes of same package which are not related
6. Classes in other packages, which are not sub-classes.

 DEPRECATED … NOT USED NOW !!!

12/15/2023 266
Private Access Specifier
 WHO CAN ACCESS
1. All members within the same class

 WHO CANNOT ACCESS


2. All members within sub-classes
3. Sub-classes present in the same package
4. Classes of same package which are not related
5. Sub-classes present in other packages
6. Classes in other packages, which are not sub-classes.

12/15/2023 267
Hierarchical Inheritance – Class Diagram
Shape
- i: int
+ Shape( )

square rectangle
- j: int - k: int
+ square( ) + rectangle( )

Hierarchical_Inheritance

+ main( ): void

12/15/2023 268
Multiple Inheritance
 A child class derives member variables
and functions from multiple parent
classes.

A: Parent class B: Parent class

C: Child class

12/15/2023 269
Multiple Inheritance – Example C++
class One { void show( ) {
protected: cout << "Vadodara" << endl;
int x; }
public: };
One( ) { x = 5; } class Three : public One, public Two
void disp( ) {
{ public:
cout << “IIIT" << endl; void printValues( ) {
} cout << x + y << endl;
}; }
class Two { };
protected: int main( ) {
int y; Three t1;
public: t1.printValues( );
Two( ) { y = 50; } t1.disp( ); t1.show( );
}
12/15/2023 270
Hybrid Inheritance
 Combination of two or more types of
inheritances.

A: Parent class

B: Child class C: Child class

D: Child class

12/15/2023 271
Hybrid Inheritance – Problem
class A
public: int x

class B : public A class C : public A


int x int x

class D : public B, C
AMBIGUOUS int x
12/15/2023 272
Hybrid Inheritance – Solution in C++
 Two ways to counter this problem in C++:

1. Scope resolution operator

2. Virtual Base class

12/15/2023 273
Hybrid Inheritance – Solution-1
class A
public: int x

class B : public A class C : public A


int x int x

class D : public B, C
B :: int x
12/15/2023 274
Virtual Base Class
class A
public: int x

class B : virtual public A class C : virtual public A


int x int x

class D : public B, C
int x
12/15/2023 275
Constructor calling - Inheritance
 Base class constructor is called by default

 First the Base class constructor is


executed, then the derived class
constructor executes.

12/15/2023 276
Constructor calling - Inheritance
class First public class
{ ConstructorCalling_Inheritance
First( ) {
{ public static void main(String args[])
System.out.println("IIIT"); {
} Second S = new Second( );
} }
class Second extends First }
{
Second( ) OUTPUT:
{
System.out.println("Vadodara"); IIIT
} Vadodara
}

12/15/2023 277
Program to Class diagram
public class Point {
public class MultipleConstructor
int x; int y; {
public Point( ) public static void main(String[]
{ args)
x = 0; {
y = 0; Point p1 = new Point(5, 2);
} Point p2 = new Point(4, 3);
public Point(int initialX, int initialY) Point p3 = new Point();
{
x = initialX; p2.translate(2, 4);
y = initialY;
} }
}
public void translate(int dx, int dy)
{
x = x + dx;
y = y + dy;
}
}
Program to Class diagram

Point
MultipleConstructor
- x: int
<<create>>
- y: int
+ main( String ) : void
+ Point( )
+ Point( int, int)

+ translate( int, int) : void


Class Diagrams
 A Class defines the attributes and the methods.

 All objects of this class (instances of this class) share the


same behaviour, and have the same set of attributes (each
object has its own set).

 Class diagrams provide a graphic notation for modeling


classes and their relationships thereby describing possible
objects.

2013: J Paul Gibson


Class Diagrams
Problem #1: 2D Geometric Objects
 Perform certain tasks on 2D shapes for example
on Polygons and Circles

 A polygon may be triangle, rectangle, and square

 Shapes can be Drawn and Color can be assigned to


the shapes

 The shape can be Moved

 Determine Perimeter and Area of a given shape.


Isosceles or Equilateral for a Triangle.
282
What do you notice?
 Regular 2D shapes can be polygons or circles

 A polygon consists of a number of points (>2)

 A polygon may be a triangle, a rectangle, square

 The other object is circle

 We can assign a color to a shape and draw it

 The shape can be moved to a position

 We should be able to determine perimeter and area of a


given shape

 In case of a triangle, we determine whether, it is equilateral


or isosceles triangle.
283
What do you notice?

284
What do you notice? Objects!

285
What do you notice? Properties!

286
What do you notice? Behavior

287
And What else?

288
And What else?

289
Classes?

290
Classes

One class per different type of objects

291
Classes

One class per different type of objects

292
Attributes

293
Attributes

294
Attributes

295
Methods

296
Methods

297
Methods

298
Methods

299
Methods

300
Final Thoughts

301
Super class vs. Sub class

Specialization: The act of defining one class as a refinement of


another.

Subclass: A class defined in terms of a specialization of a superclass


using inheritance.

Superclass: A class serving as a base for inheritance in a class


hierarchy

Inheritance: Automatic duplication of superclass attribute and


behavior definitions in subclass.
Class Diagrams
Class Diagrams
Attributes
Attributes are shown with at least their name, and can
also show their type, initial value and other properties.
Attributes can also be displayed with their visibility:
+ public attributes

# protected attributes

- private attributes

2013: J Paul Gibson


Class Diagrams
Operations

Operations (methods) are also displayed with at least


their name, and can also show their parameters and
return types. Operations can, just as Attributes, display
their visibility:

+ public operations

# protected operations

- private operations

2013: J Paul Gibson


Link & Association
• Link is a physical or conceptual connection among
objects

• Association is a description of a group of links with


common structure and common semantics
anAssociation aLink
A B anA:A aB:B
* *

anAssociation aLink

A *anotherAssociation* B anA:A aB:B


* * anotherLink

Class Diagram Object Diagram

306
Association

307
Multiplicity
Multiplicity specifies “the number of instances of one
class that may relate to a single instance of an
associated class”.

• “One” or “Many”
• Infinite (subset of the nonnegative integers)

UML Specifies multiplicity with an interval


• “1” (exactly one)
• “1..*” (one or more)
• “3..5” (three to five, inclusive)
• “*” (many)

308
Association

Visual representation

One-to-one association

Each country has one capital city


Textual representation

309
Association

Many-to-one association

Person Company
OwnStock
name name
* *

Many-to-many association

310
Association

Interpretation?
Person and Company participate in association “WorkFor”

A Person is an employee with respect to a company


A Company is an employer with respect to a Person

311
Association Class
UML offers the ability to describe links of association
with attributes like any class.

An association class is an association that is also a


class.

312
Association Class

313
Association Class vs Ordinary Class

Association Class

Ordinary Class

314
N-ary Association

Programmer

Class Diagram

315
Aggregation
 Aggregation is a special type of Association that shows “part
of” relationship

 Used to express, instances of one class are parts of an


instance of another class

 Types: Shared Aggregation and Composition

 Diamond shape is used to represent both

2013: J Paul Gibson


Shared Aggregation
 Aggregation is used where the “part” entity can exists
separately

 “Student” is the “part”

 LabClass is the “whole” in this relation

 The diamond marker is placed at the association end of the


class, which stands for the “whole”

 Solid diamond for composition

 Empty diamond for shared aggregation

 The “part” entity can exist alone/stable.

2013: J Paul Gibson


Aggregation
 Shared aggregation and Composition are

 Transitive
 if B is part of A and C is part of B, C is also part of A

 Asymmetric
 it is not possible for A to be part of B and B to be part of A
simultaneously

A B C

A B

2013: J Paul Gibson


Composition

 Composition is used where the “part” entity cannot exist


separately

 LectureHall cannot exists without Building

 Beamer may or may not be dependent upon Lecture Hall

 There can be a 1 to 0 relation between Beamer and


LectureHall.
2013: J Paul Gibson
Use-case Relationship
 Two types of Relationship between Use-cases

 Include

 Extend

 Include:

 Consists of two uses cases

 Base use case

 Inclusion use case

 “Base” use case includes functionality of “inclusion”


use case.

2013: J Paul Gibson


Use-case Relationship
 Include:

 Indicates re-usability of a task using use-case model

 Behaviour of “inclusion” use case is common for n-number of


“base” use cases

 Result or output of the “inclusion” use case is to be used by


“base” use case

 Dashed line from “base” to “inclusion”

 Arrow is pointed to “inclusion” use case

 Name of “inclusion” and “base” use cases are generally kept


outside the use-case

2013: J Paul Gibson


Use-case Relationship
 Include:

 Indicates re-usability of a task using use-case model

 Behaviour of “inclusion” use case is common for n-number of


“base” use cases

 Result or output of the “inclusion” use case is to be used by


“base” use case

 Dashed line from “base” to “inclusion”

 Arrow is pointed to “inclusion” use case

 Name of “inclusion” and “base” use cases are generally kept


outside the use-case

 “Base” mandatorily includes “inclusion” use case.


2013: J Paul Gibson
Include Use-case Relationship

The following figure illustrates an e-commerce application that provides


customers with the option of checking the status of their orders. This behavior
is modeled with a base use case called CheckOrderStatus that has an inclusion
use case called LogIn. The LogIn use case is a separate inclusion use case
because it contains behaviors that several other use cases in the system use.
An include relationship points from the CheckOrderStatus use case to the
LogIn use case to indicate that the CheckOrderStatus use case always includes
the behaviors in the LogIn use case.

2013: J Paul Gibson


Extend Use-case Relationship
 One use case extends the behaviour of another use case

 “extension” use case extends the behaviour of the “base” use case

 Relationship indicates “extended” use case is dependent on what


happens when the “base” use case executes

 There can be several “extend” use cases for one “base” use case

 Which use case can be “extend” use case

 A part of a use case that is optional system behavior

 A subflow is executed only under certain conditions

 A set of behavior segments that may be inserted in a base use


case.
2013: J Paul Gibson
Extend Use-case Relationship

 Arrow points from “extension” to “base”. Arrow head towards “base”

 Example: You are developing an e-commerce system in which you


have a base use case called Place Online Order that has an
extending use case called Specify Shipping Instructions. An extend
relationship points from the Specify Shipping Instructions use case
to the Place Online Order use case to indicate that the behaviors in
the Specify Shipping Instructions use case are optional and only
occur in certain circumstances.

Place Online Order Specify Gift Wraping


2013: J Paul Gibson
Inheritance
A: Parent class
+ x : int

B: Child class
+ x : int

• Can we access “x” variables of B and A classes


separately?

• How to call members specific to the Base/Parent


classes?
12/15/2023 326
How to call members specific to the
Base classes?

12/15/2023 327
Super - keyword
 Super keyword is used to refer parent class
entities

 Super keyword is used to access entities of parent


class from the sub-class

 Super keyword can be used in three scenarios

 Accessing variables of parent class


 Accessing methods of parent class
 Accessing constructors of parent class

12/15/2023 328
Super – keyword - Rules
 Syntax (from subclass, to access members of parent class)

 Variables: super.VariableName

 Methods: super.MethodName( )

 Constructors: super(<parameter_list>)

 It also helps to resolve conflicts between same named


entities between parent and child class
 System.out.println(variable_data); //child class variable
 System.out.println(super.variable_data); //parent class variable

 Calling parent class constructor using super from


child class constructor should be the first line.
12/15/2023 329
Constructor calling - Inheritance
class First public class
{ ConstructorCalling_Inheritance
First( ) {
{ public static void main(String args[])
System.out.println("IIIT"); {
} Second S = new Second( );
} }
class Second extends First }
{
Second( ) OUTPUT:
{
super( ); IIIT
System.out.println("Vadodara"); Vadodara
}
}

12/15/2023 330
this keyword
 this keyword is used to refer to the object which invokes the
method

 Whenever a local variable has same name as an instance variable,


then the local variable “hides” the instance variable

 this keyword helps to use same variable name for both local and
instance variables

 Syntax
 Variables: this.VariableName

 Methods: this.MethodName( )

 Constructors: this(<parameter_list>)

12/15/2023 331
this keyword
 this keyword should be the first statement within a
constructor block

 this keyword can be used to call constructor from within


another constructor

 this keyword helps to reuse the constructor

 Calling a constructor from another constructor is called as


explicit constructor invocation

 this keyword is used to call constructor of containing class


only, where super keyword is used to call constructor of
superclass.

12/15/2023 332
this keyword

this.x = x;

“x” is the instance variable Local variable of the block


referred by the current object (method or constructor)
denoted by “this”

 Calling a constructor from a normal method is not possible

 this can only call a constructor of same class from another


constructor of the same class and not from any normal
method.

12/15/2023 333
Memory Management - Objects
class ABC public class TEST
{ {
int x; psvm(String[] args)
void show( ) {
{ ABC a = new ABC( );
int x = 5; ABC b = new ABC( );
this.x = 10; System.out.println(a.x);
System.out.println(x); a.show( );
} System.out.println(b.x);
} }
}

OUTPUT: 0 5 0

12/15/2023 334
Re-defining variables in Java
 Local variable

 Instance variable

 Class variable

 Local variable:
 Variables are accessible within the block where they are declared
 Variables declared within a method/constructor are always accessible
from within the method/constructor.

 Instance variable:
 Variables that are declared within a class
 Variables which are not within a method/constructor, but inside a class
 Variables are associated with the object of the class
 All instances or objects of the class gets separate copy or memory
location of the instance variables.

12/15/2023 335
Re-defining variables in Java
 Instance methods:
 Methods that are declared within a class
 Methods are associated with the object of the class
 All instances or objects of the class gets separate copy or memory
location of the instance methods.

 Class variable:
 Variables belongs truly within the class
 All instances or objects of the class shares the same variable
 Separate memory is not allocated for the class variables with respect to
the multiple objects of the class
 Multiple instances or objects of the class do not get separate copy or
memory location of the class variables
 Class variables are called Static variables
 Methods that require similar property are called Static methods.

12/15/2023 336
Static keyword
 Static keyword helps to keep single copy of a variable or method
within a class

 Single copy with respect to the multiple objects of the class

 Static variables and methods are Object independent

 Therefore static variables and objects can be accessed directly with


the name of the class and do not need the class object/instance to
access them

 It is used when a member variable of a class has to be shared


between all the instances of the class

 Static attributes belongs to the class and not to any object of the
class.

12/15/2023 337
Static usage within Java Virtual Machine
Class Loaded

Static variables are initialized

Constructor called and instance created

Non static variables are initialized

12/15/2023 338
Static keyword - Limitations
 Overriding is not possible on static methods

 Memory is allocated once and never shares different memory

 ‘this’ and ‘super’ keywords cannot be used within a static


method.

 Syntax:

 static int x = 10;

 static int display(int x);

12/15/2023 339
final keyword
 final keyword is used to perform the following

 Makes a variable constant (value cannot be changed)


 Prevents a method from being overridden
 Prevents a class from inheriting

 final variables
 final int x = 10;
 A variable once declared FINAL, can never change its value
throughout the program.

12/15/2023 340
final methods
class T1
{
final void display( )
{
System.out.println(“Pramit”);
}
}
class T2 extends T1
{ Error. Final methods
void display( ) cannot be overridden
{
System.out.println(“Mazumdar”);
}
}
12/15/2023 341
final keyword
 final methods cannot be overridden

 final method overloading is always possible

 final methods are resolved at compile time

 final Class
 final class can contain both final and non-final attributes

12/15/2023 342
final vs static keyword
static final
Static methods cannot be overridden. Final methods cannot be overridden.
Static classes can be inherited. Final classes can never be inherited.
Static keyword can never make a Final keyword makes a variable
variable constant. It is shared by all constant.
instances of objects and has a single
copy.

Static variable can change their value Final variable once declared can
during program execution. never be changed.

These are initialized when class Final variables are accessible after
loader loads the class. the object is created.

12/15/2023 343
Controlling Inheritance
 Make a Class non-inheritable = Final

 Make class members inaccessible = private access specifier

 Allow inheritance + accessibility but work on same copy =


static

 Specific instructions in sub-classes = overriding

 Access super class elements from sub-class = super

 Duplicate names with different memory in sub-class = this

 Make a variable un-editable = final.

12/15/2023 344
Method Overriding - Example
class Bank{ class AXIS extends Bank{
int getRateOfInterest( ) int getRateOfInterest( )
{ return 0; } { return 9; }
} }
public class Method_Overriding{
class SBI extends Bank{ psvm(S a[]){
int getRateOfInterest( )
{ return 8; } SBI s=new SBI( );
} ICICI i=new ICICI( );
AXIS a=new AXIS( );
class ICICI extends Bank{ S.O.P(“SBI”+ s.getRateOfInterest( ));
int getRateOfInterest( ) S.O.P(“ICICI”+i.getRateOfInterest());
{ return 7; } S.O.P(“AXIS”+a.getRateOfInterest());
}
}
}

12/15/2023 345
Abstraction
 An essential element of object-oriented programming is
abstraction

 Humans manage complexity through abstraction

 Example; people do not think of a car as a set of tens of


thousands of individual parts. They think of it as a well
defined object with its own unique behavior

 This abstraction allows people to use a car without being


overwhelmed by the complexity of the parts that form the
car. They can ignore the details of how the engine,
transmission, and braking systems work

 Instead they are free to utilize the objects as a whole.

12/15/2023 346
Abstraction
 Process of representing essential features without including the
background details or explanations

 Only the structure of the class or a method is declared

 It does not contain any body or statement within it, i.e. they
are not defined within the class considered as abstract

 Structure or statements mentioning the tasks to be performed by


an abstract method is defined inside the corresponding subclass

 The superclass or the class considered as abstract contains only


the method declaration without any definition of how to perform a
task

 The subclass after inheritance, defines (assigns) tasks to the


abstract method in the superclass.

12/15/2023 347
Abstract in Java
abstract class test5 public class check
{ {
void show( ) { public static void main(String args[])
System.out.println("Mazumdar"); {
} check1 C = new check1( );
C.display( );
abstract void display( ); C.show( );
} }
}
class check1 extends test5
{
void display( ) { We try not to define a
System.out.println("Pramit"); normal methods
inside an abstract
}
class
}

12/15/2023 348
Abstract in Java
 Classes considered as abstract cannot have Objects

 Used in scenarios where there is no need to create object of a class


throughout the development cycle

 They are always a superclass in an inheritance, thus often known


as the abstract superclass

 Abstract class showcases a superclass from which other classes


can inherit and thus share the common design methodology

 The subclasses that inherit an abstract superclass are known as


the concrete classes, as they are actually providing the definition to
the abstract methods

 Abstract superclass is too general to create an object. They only


specify what is common among the subclasses.

12/15/2023 349
Abstract in Java
 Syntax:
abstract class test
{
……
}

 Abstract class contains multiple abstract methods

 It may also contain normal methods, constructors, and variables

 Abstract methods within an abstract class do not have any


definition

 Abstract methods are defined within the subclass after inheritance.

12/15/2023 350
Abstract properties
 Abstract methods cannot be static

 Abstract class can have instance methods/variables, static


methods/variables, final methods/variables, and constructors

 Abstract classes cannot have objects

 Abstract methods of a class MUST BE defined in the subclass. You


should not leave a method declared but not defined !!

 Constructors cannot be abstract

 Normal classes cannot contain abstract methods. Abstract


methods can only be within Abstract Classes.

12/15/2023 351
Abstract limitation
 Abstract keyword may be used to perform abstraction in Java

 An abstract superclass is extended by a normal subclass

 Abstract methods in the abstract superclass is defined within the


normal subclass

 According to Java properties, multiple inheritance is not directly


possible

 Therefore, a normal subclass can extend or define methods of a


single abstract class

 Normal subclass cannot extend multiple abstract superclasses.

12/15/2023 352
Interface
 Multiple inheritance can be performed in Java using an
Interface

 Interfaces are syntactically similar to classes

 Interfaces do not have objects

 Interfaces do not have instance variables

 Methods inside Interfaces are declared and not defined

 A single class can ‘implement’ multiple Interfaces

 Public and Default access specifier is possible within an Interface

 Private access specifier is not possible within an Interface.

12/15/2023 353
Interface
 Interface specifies what a class must do, but not how it does it

 A class can ‘extend’ a single class


 class test1 extends test2 { ……. }

 A class can ‘implement’ multiple interfaces


 class test1 implements test2, test3{ ….. }

 An interface can ‘extend’ multiple interfaces


 class test1 extends test4, test5{ ….. }

 A class can ‘extend’ a single class AND ‘implement’ multiple


interfaces
 Class test1 extends test2 implements test4, test5{ ….. }

12/15/2023 354
Interface
 Interface contains;
 Variables which are static
 Variables which are final
 Methods which are Abstract

 Abstract classes can ‘implement’ Interfaces

 All abstract methods declared in the Interface must be defined in


the implementing class

 ‘implements’ and ‘extends’ both depicts ‘is-a’ relationship.

12/15/2023 355
Package
 Packages are used to group a variety of classes and/or interfaces
together

 Grouping is done by programmer according to the functionality

 Packages provides a way of separating coding from design

 Classes contained in packages can easily be reused

 It provides a way to ‘hide’ classes thus preventing other programs


or packages from accessing classes

 A class defined within a package must be set with an access


specifier by which other package classes can access.

12/15/2023 356
Package creation
 Create a folder with same name as the desired Package name

 Create a normal java file and write the class definition within it

 First line should have,


 package <package name>;

 Access specifiers provided for the class should agree with the
requirements

 Place the java file in the same folder with the package name

 This enables to create multiple classes within the same package

 Typically classes with similar properties/objectives are kept within


the same package.

12/15/2023 357
Package creation
 Java files present in a package need not be compiled

 Classes within a package are not executed directly

 Application programs are written outside package to use the


entities present within the class

 Create a new java file. Outside the package folder. Within the same
path

 This would be the application program which would be written to


access the functionalities/methods defined/declared within classes
present in a package

 Application program (java file) that uses a class (java file) present
within a package must IMPORT it.

12/15/2023 358
Package creation
 Syntax;
 import <package name> . <classname> ; //one class within the package folder
 import <package name> . * ; //all classes within the package folder

 The application program is compiled and executed just like a


normal java file

 Separate access specifiers for class and methods within the classes

 If class is public and a method is private, then that method


would not be accessible to other classes

 Thus every method to be accessed by outside classes need to


be assigned the correct access specifier.

12/15/2023 359
Elements of Object Models
 Four major elements of the Object Model

 Abstraction

 Encapsulation

 Modularity

 Hierarchy

 Three minor elements of the Object Model (useful but not


essential)

 Typing

 Concurrency

 Persistence

12/15/2023 360
Concurrency
 Concurrency is the property that distinguishes an active
object from one that is not active

Object 1 Object 2

Object 3

 Should we design a system which states how or in which sequence


the messages should flow?

 We need to design a system in which at any point of time … any


object can send any message and can operate on any data …
without any restrictions …. Yet the system must run smooth !!

12/15/2023 361
Concurrency
 Possible scenarios:
 Object 1 is sending a message to Object 2 requesting for a service

 Object 1 is receiving a message from Object 3 to provide a service

 System should be designed and implemented in such a way that


both are possible at a give time instance

 Similarly at the same instance there might be other objects in the


system who are in an idle state doing nothing

 A Client-Server model can never function without enabling


Concurrency !!

 We should never create a situation where we define which


object sends what message at what timestamp, such
scenario would take the fun of using a system !!

12/15/2023 362
Concurrency
 Allows multiple tasks to execute, interact, and collaborate at
the same time to achieve the global functionality

12/15/2023 363
Concurrency: Heavyweight and Lightweight
 Heavyweight Concurrency:

 Typically independently managed by the target OS and has its own


address space

 Communication among heavyweight processes is expensive and involves


inter-process communication

 Commonly called as Process

 Lightweight Concurrency:

 It lives within a single OS process along with other lightweight processes


and share the same address space

 Communication among lightweight processes is less expensive and often


involves shared data

 Commonly called Thread.

12/15/2023 364
Process
class T1 Java code
{
public static void main(String args[])
{ Compile
int sum = 0;

for( int i=0; i < 10000000; i++ ) Interpret


{
sum = sum + i;
Executable
}
}
}
Process

12/15/2023 365
Process
 Problem: Loop would run from 0 to 10000000 (10 million) times

 Addition needs to be done at each step

 10 million number of times the same set of instructions (tasks)


need to be performed

 The numbers after 5 million need to wait for execution until the
numbers before them are executed.

Processor 1 Processor 2 Processor 3 Processor 4

12/15/2023 366
Process
Java code Compile Interpret Executable

A program in
execution is Process
called Process

Processor 1 Processor 2 Processor 3 Processor 4

12/15/2023 367
Process
 Only one processor is used

 Other processors are left unused

 Time consuming

 Optimized execution would be to utilize all the processors present


in the system

 Solution:
 Divide the task into parts
 10 million can be divided into 4 parts (2.5 million each)
 Each task can be assigned separate process
 4 processes each with 2.5 million numbers
 Each process assigned to separate processors
 4 process executes on 4 processors

12/15/2023 368
Process
Java code Compile Interpret Executable

Process Process Process Process


1 – 2.5m 2.5 – 5m 5 – 7.5m 7.5 – 10m

Processor 1 Processor 2 Processor 3 Processor 4

12/15/2023 369
Process
 What we achieved:
 Parallelization is achieved
 Speed up the execution

 The processes are isolated from each other

 Thus each process has its own;


 Set of instructions

 Data

 Heap

 Stack, etc.

 Question: Finally the results of each process needs to


be combined …. Who does that .. Who monitors it??

12/15/2023 370
Process
 Interprocess communication (IPC) which communicates
among the processes in execution

 Either they keep track of the execution timeline of each


process running in parallel

 Or they provide a separate shared memory where results of


each parallel process is stored, and eventually used for
computing the final result

 This mechanism is extremely expensive

 It is desired not to rely on such mechanism if


alternative is available.

12/15/2023 371
Process
 Why creation of 4 separate process is a problem?

 All process execute same set of instruction (adding


values)

 All process access the same array (from a different


location)

 So instructions and data are duplicated in all the 4


parallel processes

 THREADS can help in addressing this problem.

12/15/2023 372
Thread
 Threads are extremely light weight when compared to
processes

 They require less resources than a complete process

 Instead of creating 4 parallel processes. We may


consider creation of 4 parallel threads

 Assign 4 threads to 4 processors present in the system

 One process => 4 threads => 4 processors

 Each thread with 2.5million numbers.


12/15/2023 373
Thread
Java code Compile Interpret Executable

Process

Thread Thread Thread Thread


1 – 2.5m 2.5 – 5m 5 – 7.5m 7.5 – 10m

Processor 1 Processor 2 Processor 3 Processor 4

12/15/2023 374
Process
Java code Compile Interpret Executable

Process Process Process Process


1 – 2.5m 2.5 – 5m 5 – 7.5m 7.5 – 10m

Processor 1 Processor 2 Processor 3 Processor 4

12/15/2023 375
Thread
Thread Process
Thread has no data segment or heap Process has code, heap, stack, and
to store/access data other segments as well
Thread cannot live on its own. It is A process can execute independently.
always associated with a process
There can be one of more threads Every process has at least one thread
associated with a process for execution

Threads within a process share the Separate process have separate


same code, resources, etc. code, memory, resources, etc.
Thread has its own Stack. On thread If a process dies, all its threads are
destroy the stack is reclaimed by the also destroyed.
host process.

12/15/2023 376
Thread
 A sequential program has only one single flow of
control

 Thus at any one timestamp there is only one


instruction that is being executed

 A program written sequentially also consists of only


one thread that initiates the execution process

 A multithreaded program has multiple flows of control


when executed

12/15/2023 377
Thread
 A program is divided into a number of parts

 Each part defines a specific task

 Each task/part of the program is called as the


threads of the program

 Multithreaded program is one which consists of


multiple threads within it and all threads run in
parallel, known as Multithreading.

12/15/2023 378
Thread
 Process is an isolated execution entity which has its
own code, heap, stack, and other segments

 Thread does not have its own data segment and heap

 Thread uses the data segment and heap of host


process

 A thread within a process will use the same


resources as allocated to the host process

 Thus process in itself is a complete entity and


thread is a part of it.

12/15/2023 379
Thread
 A process cannot execute without a thread

 “main” is one thread that always executes in a


program

 Threads in java can be considered as sub programs of


the main application program which shares the same
memory space

 Threads in Java can be executed in parallel thus


boosting parallelism through Java.

12/15/2023 380
Thread

12/15/2023 381
Thread
class ABC
{
public static void main(String x[])
{
……
……
}
}

Single Thread

12/15/2023 382
Thread
Thread A

Switching

main thread Thread B

Switching

Thread C

Multithreading

12/15/2023 383
Life Cycle of a Thread
Ready for
New Born execution, but
CPU may waiting for
release a CPU
running start( )
allocation.
thread.
Ready

yield( ) run( )

Running
CPU is
stop( ) allocated and
is executing.

Dead

12/15/2023 384
Life Cycle of a Thread
1. NEW BORN

 A thread is started in this stage

 To start a thread we need to create an object

 Also allocate a working memory space for the thread

 This memory location is allocated within the memory for the


process within which the thread works

12/15/2023 385
Life Cycle of a Thread
2. READY or RUNNABLE

 The thread is already created

 After memory allocation in “New Born” stage, the thread needs to


be brought to the Ready state

 start( ) is the only method that can be used for starting a new
thread

 start( ) brings a new born thread to a ready state

 Here the thread is ready to be executed, but have not been


allocated any processor for execution (CPU unavailability).

12/15/2023 386
Life Cycle of a Thread
3. RUNNING

 run( ) method is used to allocate CPU to the thread

 The thread is in execution if run( ) method is executed properly

 run( ) method describes the task which the thread is going to


perform

 Instructions written within the run( ) method describes what the


thread is going to perform

12/15/2023 387
Life Cycle of a Thread
4. DEAD

 On completion of execution of instructions present in run( )


method

 Thread is moved to Dead state

 Otherwise we can use stop( ) method to stop execution of a


thread

 stop( ) method can be used to move a thread from running state


to dead state

 A thread in dead state cannot be brought back to running or


ready state.

12/15/2023 388
Thread program in Java
 Threads can be created in Java using;

 Create a class which extends Thread parent class

 Create a class which implements the Runnable interface

 Thread parent class


 Primary class that helps to implement Multithreading in Java

 java.lang.Thread => Thread class is present in java.lang package

 Import java.lang to use Thread class

 start( ) and run( ) methods are available within Thread class.

12/15/2023 389
Thread program in Java
 Runnable interface

 Interface present within java.lang package

 Only abstract method run( ) is present

 No other methods present in Thread class is available here

 To start a thread using Runnable interface,

 We need to create object of Thread class

 Pass the object of the class along with the Thread object

 Use the Thread object to call start method.

12/15/2023 390
Thread programs
 REFER PROGRAMS

 thread_eg1.java

 thread_eg2.java

12/15/2023 391
Life Cycle of a Thread
New Born

start( )

Ready

yield( ) run( )

Running

stop( )

Dead

12/15/2023 392
Life Cycle of a Thread
New Born

start( )
after t secs.
Ready

Wait
yield( ) run( )

Running

stop( )
Sleep
Dead

12/15/2023 393
Life Cycle of a Thread
 sleep( ) [paused execution]
 Java pauses the thread for a specified seconds (user defined)
 Thread does not lose its ownership
 Thread resumes execution after the specified time is over
 CPU allocation is managed accordingly, so that after specified time it
can be brought back to running state
 Failures of automatic transition from ready to running state may be
disrupted in a few extra-ordinary scenarios.

 wait( ) [inter-thread communication]


 Method is defined in java.lang.Object class
 Threads are not moved to ready queue directly on execution wait( )
 This method makes a thread wait until the notify( ) method is called
 notify( ) method brings a thread from waiting state to ready state and
wait for CPU allocation
 On CPU allocation the thread restarts execution.

12/15/2023 394
Life Cycle of a Thread
New Born

start( )

Ready

Blocked yield( ) run( )

Running

stop( )

Dead

12/15/2023 395
Life Cycle of a Thread
New Born

start( )

Ready

yield( ) run( )

Running

stop( )

Dead

12/15/2023 396
Life Cycle of a Thread
New Born

start( )
after t secs.
Ready

Wait
Blocked yield( ) run( )

Running

stop( )
Sleep
Dead

12/15/2023 397
Thread programs
 REFER PROGRAMS

 thread_eg3.java

 thread_eg4.java

12/15/2023 398
Thread Priority
 Priority to threads can be set

 Execution of threads are performed as per their priority

 Syntax:
 <ThreadName>.setPriority ( int Number )

 Priority ranges between 10 to 1 (highest to lowest)

 5 is the default priority

 <thread name>.MAX_PRIORITY, <thread name>.MIN_PRIORITY,


<thread name>.NORM_PRIORITY

 <thread name>.setPriority( ) , <thread name>.getPriority( )

12/15/2023 399
Thread programs
 REFER PROGRAMS

 thread_eg5.java

 thread_eg6.java

12/15/2023 400
Synchronization
 A thread may try to read a resource which is now been used by
another thread

 Thus depending upon the instructions in both the threads, the


results may vary

 This is due to the fact that both the threads are accessing the
same resource

 Synchronization technique is used in Java to address the problem

 If a method is declared to be synchronized then, whenever a


thread calls this method for first time a Monitor is created over the
method

 Thus other methods are restricted from calling the same method.

12/15/2023 401
Synchronization
 Therefore multiple threads may not access a single data/method at
the same time

 Syntax:
synchronized void display( )
{
……
……
}

 A monitor is an object that is used as a mutually exclusive


lock or mutex

 Monitor allows one thread at a time to execute a synchronized


method on the object.

12/15/2023 402
Exception Handling
 Any error during program execution may produce incorrect output

 Even can terminate the program

 In some scenarios could halt the system

 Java provides a way to handle errors

 Types of errors;
 Compile time error
 Run time error

 Compile time errors:


 Syntax errors in program coding
 Detected and displayed on screen
 Class file is not created in this scenario.

12/15/2023 403
Exception Handling
 Run time errors:
 Programs may be compiled correctly and class file could be created
 However, the program may fail to execute
 Alternatively it may produce wrong results due to wrong logic in the
programs
 For example;
 Dividing an integer by zero
 Accessing an element which is out of an array limit, etc.

 Exception
 Refers to an unwanted or unexpected event
 That may occur during the execution of a program (runtime)
 Disruption in program flow may occur
 If such an exception is not handled then an error message is displayed
 And the program is terminated

 It is desired to keep the program in execution and handle the


unexpected event or exception.

12/15/2023 404
Exception Handling
ERROR EXCEPTION

Lack of system resources and The program code in execution


some scenarios related to the generates an exception
environment/resources in which
the program is executing

Error cannot be recovered. Once Exception can be handled and


occurred, the program execution recovered. Does not affect
is stopped program execution (if handled)

Errors are present in Exceptions are present in


java.lang.Error package java.lang.Exception package
Examples: Examples:
Syntax errors, Logical errors, ArrayIndexOutOfBoundException,
OutOfMemoryError, ArithmeticException, IOException,
StackOverflowError, etc. etc.

12/15/2023 405
Exception Class Hierarchy

12/15/2023 406
Exception Handling
 If we want to continue execution of the remaining code

 We must hold or catch the exception

 Subsequently display an appropriate message

 Continue execution of the rest of the program

 Exception handling tasks:

 Find the problem (Hit the exception)

 Inform error has occurred (THROW exception)

 Receive error information (CATCH exception)

 Take corrective action (Handle exception)

12/15/2023 407
Exception Handling
TRY Exception
object creator
Statement that causes
exception
Throws exception object

CATCH
Exception handler
Statement that handles
the exception

12/15/2023 408
Exception Handling
 Exception handling has two parts; TRY and CATCH

 Code which is likely to cause an error condition is kept in TRY

 Catch block handles the exception thrown by the try block

 Catch block also contains instructions for handling the exceptions

 If an exception occurs within the try block then

 Control jumps from try block to catch block

 Searches for the correct catch block that handles the occurred
exception

 Control never goes back from Catch to Try block.

12/15/2023 409
Exception Handling
 Code written within the catch block is executed for handling the
exception

 After execution, the control goes to the next line of the instruction
after the Catch block

 Exception occurred only within a try block is handled in the


corresponding catch block

 Exceptions created outside try block is never caught, and stops


program execution.

12/15/2023 410
Exception Handling
try
{
……..
……..
}
catch(Exception_Type e)
{
…………
…………
System.out.println( e.getMessage );
}

//Exception_Type is the type of exception to be handled

//Superclass for every exception is Exception

12/15/2023 411
Exception Handling
try
{
……..
……..
}
catch(Exception e)
{
…………
…………
System.out.println( e.getMessage );
}

//All exception can be handled using Exception class

 Control from a Catch block never comes back to Try block.

12/15/2023 412
Exception Handling
 A try block can have multiple catch blocks

 The specific exception types are placed at the beginning

 Catch block with Exception class is kept at the last

 So that if specific exception is not handled then Exception class


can handle

 There should not be any lines between TRY and CATCH

 FINALLY BLOCK:
 Instructions written within Finally block is bound to execute

 Instructions written within Finally block does not depend on whether


exception occurred or not.

12/15/2023 413
Exception Handling
 Instructions which must be executed in a program might be kept
in the Finally block

 Syntax:
try
{
……
}
catch(Exception e)
{
…..
}
finally
{
……
}

12/15/2023 414
Exception Handling
 A message is generated by the JVM on encountering an exception

 The message contains the type of exception that occurred

 The line number where the exception has occurred, etc.

 printStackTrace( ) method can be used to print this statement

 However, we can also provide our own customized message

 Refer Program: exception_eg5.java

12/15/2023 415
Exception Handling
TRY Exception
object creator
Statement that causes
exception
Throws exception object

CATCH
Exception handler
Statement that handles
the exception

12/15/2023 416
Exception Handling
try
{
……..
……..
}
catch(Exception_Type e) {
…………
…………
System.out.println( e.getMessage );
}

catch(Exception e) {
…………
…………
System.out.println( e.getMessage );
}

12/15/2023 417
Throw Exception
public class exception_eg1 {
public static void main(String args[])
{
try
{
int x[] = new int[5];
x[20]=10;
System.out.println(“Pramit”);

}
catch(ArrayIndexOutOfBoundsException e)
{
e.printStackTrace();
}
} }

12/15/2023 418
Throw Exception
 Usually exception is automatically identified and thrown by the
JVM

 Unless it is manually identified and handled by programmer

 Throwing of exceptions can also be done manually

 Instructions to be displayed can be set according to requirements

 Syntax:

throw new ArrayIndexOutOfBoundsException ( “Here goes the Instruction” )

 Refer program: exception_eg2.java

12/15/2023 419
Throw Exception
public class exception_eg2 {
public static void main(String args[ ]) {
try {
int x[ ] = new int[5];
x[4]=10;

throw new ArrayIndexOutOfBoundsException("Array is


almost FULL !!");
}
catch(ArrayIndexOutOfBoundsException e)
{
e.printStackTrace( );
}
}
}

12/15/2023 420
Throw User-defined Exception
 User-defined exceptions can also be created

 User-defined exceptions would have user-defined statements, which would


be displayed to the user

 To manually throw a pre-defined exception we create an object of the


required exception

 Syntax:
 throw new ArrayIndexOutOfBoundsException ( “Here goes the Instruction” )

 However for user-defined exception we do not have a pre-defined class for


which we can create the object

 Therefore, as the first step we would create class for the user-defined
exception, that extends the Exception class

 Rest remains same. Refer Program: exception_eg3.java

12/15/2023 421
Throw Exception
class my_exception extends throw new my_exception("\n You
Exception are approaching the Array Limit !!
{ \n");
my_exception(String msg)
{ }
super(msg); catch(my_exception e) {
} System.out.println(e.getMessage( ));
} }
} }
public class exception_eg2 {
public static void main(String
args[ ]) {
try {

int x[ ] = new int[5];


x[4]=10;

12/15/2023 422
Throws Exception
 Throw keyword can only be used if we want to handle an exception
from the same method

 It is not possible that the exception occurs at one method and it is


handled in another method: if we use Throw keyword

 Throws keyword can be used to address this problem

 Usual Scenario:

 Class 1 with Method 1 and Class 2 with Method 2

 Method 1 throws an exception

 That exception is handled in Method 1

 Method 2 throws exception which is handled in Method 2

12/15/2023 423
Throws Exception
 New Scenario:

 Class 1 with Method 1 and Class 2 with Method 2

 Method 1 throws an exception

 That exception is handled in Method 2

 Method 2 throws an exception

 That exception is handled in Method 1

 Refer Program: exception_eg4.java

12/15/2023 424
Throw Exception
class test_throws try
{ {
void disp() throws T.disp( );
ArithmeticException, Exception }
{
int x = 7/0; catch(ArithmeticException e) {
}
} e.printStackTrace( );

public class exception_eg4 }


{ catch(Exception e) {
public static void main(String args[]) e.printStackTrace();
{ }
test_throws T = new test_throws(); }
}

12/15/2023 425
Elements of Object Models
 Four major elements of the Object Model

 Abstraction

 Encapsulation

 Modularity

 Hierarchy

 Three minor elements of the Object Model (useful but not


essential)

 Typing

 Concurrency

 Persistence

12/15/2023 426
Persistence
 Persistence is the property of an object through which its
existence transcends time

 Once an object is created


 It occupies certain memory space
 It stays for a certain time

 Persistence is the relationship of an object with “time” and


“space”

 Time: Object continues to exist after its creator ceases to


exist

 Once the creator no longer exists then how long will the
object stay or exist is an independent decision taken by OS

 Space: Object’s location moves from the address space in


which it was created.

12/15/2023 427
Continuum of Object Existence
 An object in software takes up some amount of space and exists for
a particular amount of time

 There is a continuum of object existence, ranging from transitory


objects that arise within the evaluation of an expression to objects
in a database that outlive the execution of a single program

 Transitory objects: objects that are created temporarily, for an


interim operation. Example: return a variable with the value and
store the returned value within the original variable of the program.
So the variable which brings the value from the called function to
the calling function is temporary/ interim object and we do not
need it later

 Objects in DB/Persistent Objects: An object/ data stored in DB


for representing an employee. Now the employee may have left. The
operation/interface/functionality given to that user, might be
removed as he/she has left. However, the object pointing to that
employee may remain for more duration (outlive).

12/15/2023 428
Continuum of Object Existence
 Spectrum of object persistence: EXAMPLES

 Transient results in expression evaluation

 Local variables in function invocation

 Global variables and heap items whose extent is different


from their scope

 Data that exists between executions of a program

 Data that exists between various versions of a program

 Data that outlives the program.

12/15/2023 429
Why Persistence is Important?
 If an object is very transitive, i.e. it occurs and then
disappears then we would like to use a lightweight process
for the task/object

 If not then system would have a lot of overhead in creating


and destroying the objects

 If an object is very large and takes a lot of space then we


must ensure that it is having more persistent behaviour
than transitive behavior

 Large objects or objects in DB which is regularly used (for


storage or relocation) should be treated separately so that
we do not have system performance issues.

12/15/2023 430
Garbage Collection
 JVM maintains a heap to store all objects created by a running
java application

 Garbage collection is the process of automatically freeing objects


that are no longer referenced by the program

 This is also called memory recycling theory

 When an object is no longer referenced/ used by the program, the


heap space it was occupying can be used by other new objects

 Very effective for memory management

 Garbage collector determines the object which is not referenced by


the program for a certain duration of time.

12/15/2023 431
Garbage Collection
 Garbage collector is a part of the JVM which significantly helps in
memory management related to Java programs

 Programmers do not need to explicitly identify objects which are


currently not in use

 Garbage collector ensures program integrity

 Programmers do not have the control to delete an object from


memory

 This ensures incorrectly freeing of memory and thus preventing


accidental crash of JVM

 Garbage collection is executed using a Daemon thread, which


always runs in the background.

12/15/2023 432
Finalize
 Finalize is a method present in java.lang.Object class

 Every class by default inherits the finalize( ) method

 The daemon thread for garbage collection always runs in behind

 Garbage collection process automatically identifies the un-used


objects and free them from memory

 Programmers are not notified when an un-used object is being


deleted from memory

 However, we can programmatically provide a notification system


which would be invoked on deletion of an object.

12/15/2023 433
Finalize
 finalize( ) method can be used for this purpose

 A garbage collector before deleting an object searches for finalize( )


method if present

 If present, the method is executed and customized instruction can


be provided to the programmer

 If any exception is thrown by the finalize method then the entire


finalization process is blocked.

 REFER PROGRAM: finalize_eg.java

12/15/2023 434
Finalize
class test_finalize {
protected void finalize( ) {
System.out.println("Object Deleted !!");
}
}

public class finalize_eg {


public static void main(String args[ ]) {
for(int i=0; i<5; i++)
{
test_finalize x = new test_finalize();
}

System.gc( );
}
}

12/15/2023 435
Sequence Diagram

12/15/2023 436
Sequence Diagram

12/15/2023 437
Lifeline in a Sequence Diagram

12/15/2023 438
Objects and Lifeline

12/15/2023 439
Objects and Life Time

12/15/2023 440
Start and End of Life Line

12/15/2023 441
Messages in Sequence Diagram

12/15/2023 442
Synchronous and Asynchronous Messages

12/15/2023 443
Lost and Found Message

12/15/2023 444
Self or Recursive Message

12/15/2023 445
Controlled Message

12/15/2023 446
Duration and Timing Constraints

12/15/2023 447
UML: Sequence diagram
Actor Message Object Lifeline

:WatchUser :Watch :LCDDisplay :Time


pressButton1() blinkHours()
pressButton1()
blinkMinutes()
pressButton2()
incrementMinutes()
refresh()
pressButton1and2()
commitNewTime()
stopBlinking()
Activation

Sequence diagrams represent the behavior of a system


as messages (“interactions”) between different objects
State Machine Diagram _ Sample Example
button1&2Pressed button2Pressed
Blink Increment
Hours Hours

button1Pressed

button1&2Pressed button2Pressed
Blink Increment
Minutes Minutes

button1Pressed

button2Pressed
Stop Blink Increment
Blinking Seconds Seconds

12/15/2023 449
State Machine Diagram _ States

12/15/2023 450
Transition _ Self Transition

12/15/2023 451
Compound State

12/15/2023 452
Entry _ Exit States

12/15/2023 453
Choice Pseudo State

12/15/2023 454
Junction Pseudo State

12/15/2023 455
Terminate Pseudo State

12/15/2023 456
Terminate Pseudo State

12/15/2023 457
History State

12/15/2023 458
Concurrent Regions within a State

12/15/2023 459
Concurrency in State Diagram

12/15/2023 460
UML: Statechart diagrams

 Represent behavior of single objects with interesting dynamic


behavior in terms of states and transitions

 The behavior of the single object Watch, for example, has several
different interesting states, BlinkHours, BlinkMinutes, BlinkSeconds,,
etc.

 Because in each state pressing a button or two yields a different


result.
State Machine Diagrams
A State chart diagram shows the lifecycle of an object
• A state is a condition of an object for a particular time
• An event causes a transition from one state to another state
• Here is a State chart for a Phone Line object:

state
initial State

event

transition
When to develop a state chart?
Model objects that have change state in interesting ways:
 Devices (microwave oven, Ipod)

 Complex user interfaces (e.g., menus)

 Transactions (databases, banks, etc.)

 Stateful sessions (server-side objects)

 Role mutators (what role is an object playing?)

 Etc.
UML: Statechart diagrams
Event Initial state

button1&2Pressed button2Pressed
Blink Increment
Hours Hours

Transition button1Pressed

button1&2Pressed button2Pressed
Blink Increment
Minutes Minutes
State

button1Pressed

button2Pressed
Stop Blink Increment
Blinking Seconds Seconds

Final state

Represent behavior of a single object with interesting dynamic behavior.


State Machine Diagrams
 A state machine diagram models the  The door can be in one of three
behavior of a single object, specifying states: "Opened", "Closed" or
the sequence of events that an object "Locked". It can respond to the events
goes through during its lifetime in Open, Close, Lock and Unlock.
response to events. As an example, Notice that not all events are valid in
the following state machine diagram all states; for example, if a door is
shows the states that a door goes opened, you cannot lock it until you
through during its lifetime. close it. Also notice that a state
transition can have a guard condition
attached: if the door is Opened, it can
only respond to the Close event if the
condition
 doorWay->isEmpty is fulfilled. The
syntax and conventions used in state
machine diagrams will be discussed in
full in the following sections.
State Machine Diagrams
 States - A state is denoted by a round-cornered rectangle with the
name of the state written inside it.

• Initial and Final States - The initial state is denoted by a filled black circle
and may be labeled with a name. The final state is denoted by a circle with
a dot inside and may also be labeled with a name.
State Machine Diagrams
• Transitions - Transitions from one state to the next are denoted
by lines with arrowheads. A transition may have a trigger, a guard
and an effect, as below.
• Self-Transitions - A state can have a transition that returns to
itself, as in the following diagram. This is most useful when an
effect is associated with the transition.

• "Trigger" is the cause of the transition, which could be a signal, an


event, a change in some condition, or the passage of time. "Guard"
is a condition which must be true in order for the trigger to cause
the transition. "Effect" is an action which will be invoked directly
on the object that owns the state machine as a result of the
transition.
State Machine Diagrams
• State Actions - In the transition example above, an effect was
associated with the transition. If the target state had many
transitions arriving at it, and each transition had the same effect
associated with it, it would be better to associate the effect with
the target state rather than the transitions. This can be done by
defining an entry action for the state. The diagram below shows a
state with an entry action and an exit action.

• It is also possible to define actions that occur on events, or actions


that always occur. It is possible to define any number of actions of
each type.
State Machine Diagrams
 Compound States - A state machine diagram may include sub-
machine diagrams, as in the example below.

Alternative
way to show
the same
information
•The ∞ symbol indicates that details of the Check PIN
sub-machine are shown in a separate diagram.
State Machine Diagrams
 Entry Point - Sometimes you won’t want to enter a sub-machine at
the normal initial state. For example, in the following sub-machine it
would be normal to begin in the "Initializing" state, but if for some
reason it wasn’t necessary to perform the initialization, it would be
possible to begin in the "Ready" state by transitioning to the named
entry point.

• Exit Point - In a similar manner to entry points, it is possible to


have named alternative exit points. The following diagram gives an
example where the state executed after the main processing state
depends on which route is used to transition out of the state.
State Machine Diagrams
 Choice Pseudo-State - A choice pseudo-state is shown as a
diamond with one transition arriving and two or more transitions
leaving. The following diagram shows that whichever state is
arrived at, after the choice pseudo-state, is dependent on the
message format selected during execution of the previous state.
State Machine Diagrams
 Junction Pseudo-State - Junction
pseudo-states are used to chain
together multiple transitions. A
single junction can have one or
more incoming, and one or more
outgoing, transitions; a guard can
be applied to each transition.

 A junction which splits an


incoming transition into multiple
outgoing transitions realizes a
static conditional branch, as
opposed to a choice pseudo-state
which realizes a dynamic
conditional branch.
State Machine Diagrams
• Terminate Pseudo-State - Entering a terminate pseudo-state
indicates that the lifeline of the state machine has ended. A
terminate pseudo-state is notated as a cross.

• History States - A history state is used to remember the previous


state of a state machine when it was interrupted. The following
diagram illustrates the use of history states. The example is a state
machine belonging to a washing machine.
State Machine Diagrams
• Concurrent Regions - A state may be divided into regions
containing sub-states that exist and execute concurrently. The
example below shows that within the state "Applying Brakes", the
front and rear brakes will be operating simultaneously and
independently. Notice the use of fork and join pseudo-states,
rather than choice and merge pseudo-states. These symbols are
used to synchronize the concurrent threads.
Concurrency in state diagrams
 Dashed line indicates that an order is in two different states, e.g.
Checking & Authorizing
 When order leaves concurrent states, it’s in a single state: Canceled,
Delivered or Rejected
State Transitions – notational variation

476
Thank You

12/15/2023 477

You might also like