SKILLWISE-OOPS
CONCEPT
Core & Advanced Java – Alpha
Batch
Unit- I OOPS Concepts
Topics
• OOP and its characteristics
• OOP and its advantages
• Understanding Classes and Objects
• Encapsulation and Abstraction
• Inheritance and Polymorphism
• Object Interaction - Services/Methods/Functions
• Object Relationship - Association, Aggregation
and Composition
• Understanding UML
Structured Programming
• Structured programming
– the data and the operations on the data are separate.
• Data structures are created to hold attributes and is sent to functions to
be operated on.
• Link between functions and data is function parameter.
• In an event of changes to Person , coder has to search for all places where
data structure is being used and has to be modified.
Public class Person
{ int id;
String name;
}
public void add (Person p)
{.....}
public void remove (Person P)
{.....}
Object Oriented Programming
• It has been around since 1967.
• Popular programming paradigms in the mid-1980s .
• In OOP data and operations are part of the same entity.
• Closely models the real world, in which all objects have both
attributes and code associated with them.
• No need to pass in a reference to a Data structure as Methods
implicitly know about the variables of their class and have full
access to them.
Public class Person
{
int id;
String name;
public void add() {.....}
public void remove() {.....}
}
Structured Versus Object Oriented
Programming
• Structured programming
– Data lies separate from code.
– No data abstraction or info hiding.
– Programmer is responsible for organizing everything in to logical
– units of code/data.
– No help from compiler/language for enforcing modularity.
• Object Oriented Programming
– Model everything as objects.
– Keep data near the relevant code.
– Avoid reinventing the wheel.
– Easier to understand, manage and maintain.
– Simplify testing and debugging.
Benefits of OOP
• Promotes and facilitates software reuse.
– Save development time and cost
– Enables Easy Debugging
– Classes can be tested independently
– reused objects have already been tested
• Facilitates interoperability
• Results in software that is easy to modify, extend and maintain
• Reduces integration effort
• Some of the Popular OOP Languages
– Simula,C++,SmartTalk,Java
Features of OOP
• Natural
• Reliable
• Reusable
• Maintainable
• Extendable
• Timely
Natural & Reliable
• OOP produces natural software. Natural programs are more understandable.
• Instead of programming in terms of an array or region of memory, programs
uses the terminology of the particular problem.
• Model a problem at a functional level, not at the implementation level
• The modular nature of objects allows to make changes to one part of program
without affecting other parts.
• Objects isolate knowledge and responsibility where they belong.
• One way to increase reliability is through thorough testing.
• Isolation allows to test and validate each component independently. Once
validated ,it can be reused
Reusable & Maintainable
• Objects can be reused in many different programs. ,inheritance allows
to extend existing objects and polymorphism to write generic code.
• OOP can model general ideas and use those general ideas to solve
specific problems.
• In order to fix a bug, simply correct the problem in one place.
• Change to the implementation is transparent, all other objects will
automatically benefit from the enhancement.
• The natural language of the code should enable other developers to
understand it as well.
Timely & Extendable
• A library of objects, extend your own objects’ functionality.
• OOP aids these quick development cycles. OOP trims time off of the
development cycle by providing reliable, reusable, and easily
extendable software.
• When you break down a program into a number of objects, the
development of each piece can go on in parallel.
• Multiple developers can work on classes independently. Such parallel
development leads to quicker development times
OOP Characteristics
• Encapsulation - Enforces Modularity
– Encapsulating the data and behavior into a single object is of primary
importance in OO development. A single object contains both its data
and behaviors and can hide what it wants from other objects.
• Inheritance -Passes "Knowledge" Down
– A class can inherit from another class and take advantage of the
attributes and methods defined by the superclass.
• Polymorphism -Takes any Shape
– Polymorphism means that similar objects can respond to the same
message in different manners.
• Composition – Organizes objects
– Composition means that an object is built from other objects.
Encapsulation
• It is the ability of an object to place a
boundary around its properties (data,
methods).
• It seals the data and methods safely inside the
'capsule' of a class, where it can be accessed
only by trusted users (ie methods of the class).
• While driving a car, user don't have to know the details of cylinders,
ignition etc.
Why Should Encapsulate
• Reuse the object anywhere.
• Upgrade component, by providing a more efficient implementation, or fix
bugs—all without having to touch the other objects in your program.
• The users of your object automatically benefit from any changes that you
make.
• Using an encapsulated object won’t cause unexpected side effects
between the object and the rest of the program. Since the object is self-
contained,
• it won’t have any other interaction with the rest of the program beyond
its interface.
Abstraction Principle
• Abstraction is the ability to focus on the
important features of an object when trying to
work with large amounts of information.
• Example,
– if we are trying to design a floor plan for a kitchen,
we can focus on the shapes and relative sizes of
the appliances and ignore attributes such as color,
Effective Abstraction
• Address the general case, not the specific case.
• When confronting a number of different problems, search for commonality.
Try to see a concept, not a specific case.
• Abstraction might not be readily apparent. Abstraction might not jump out at
you the first, second, or third time you solve a problem that is subject to
being abstracted.
• Prepare for failure. It is almost impossible to write an abstraction that will
work in every situation.
Inheritance
• Inheritance is unique to OO
– not there in function-oriented languages/models
• Inheritance by class B from class A is the facility by which B implicitly gets
the attributes and operations of A as part of itself
• Attributes and methods of A are reused by B
• When B inherits from A, B is the subclass or derived class and A is the base
class or superclass
Inheritance..
• A subclass B generally has a derived part (inherited from A) and an
incremental part (is new)
• Hence, B needs to define only the incremental part
• Creates an “is-a” relationship
– objects of type B are also objects of type A
Inheritance…
Inheritance…
• The inheritance relationship between classes forms a class hierarchy
• In models, hierarchy should represent the natural relationships present in
the problem domain
• In a hierarchy, all the common features can be accumulated in a superclass
• An existing class can be a specialization of an existing general class – is
also called generalization-specialization relationships
Inheritance…
• Strict inheritance – a subclass takes all features of parent class
• Only adds features to specialize it
• Non-strict: when some of the features have been redefined
• Strict inheritance supports “is-a” cleanly and has fewer side effects
Inheritance…
• Single inheritance – a subclass inherits from only one superclass
• Class hierarchy is a tree
• Multiple inheritance – a class inherits from more than one class
• Can cause runtime conflicts
• Repeated inheritance - a class inherits from a class but from two separate
paths
Diamond Problem
When an object of class D, any calls to method definitions in class A will be
ambiguous – because it’s not sure whether to call the version of the method
derived from class B or class C.
Inheritance and Polymorphism
• Inheritance brings polymorphism, i.e. an object can be of different types
• An object of type B is also an object of type A
• Hence an object has a static type and a dynamic type
• Implications on type checking
• Also brings dynamic binding of operations which allows writing of general
code where operations do different things depending on the type
Inclusion polymorphism
• Its pure polymorphism, allows you to treat related objects generically.
• Parametric polymorphism
– allows to create generic methods and generic types,generic methods
and types allow you to code something once and have it work with
many different kinds of arguments.
• Overriding
– is an important type of polymorphism.
• Overloading
– also known as ad-hoc polymorphism, allows you to use the same
method name for many different methods. Each method only differs in
the number and type of its parameters.
Method Overloading
• This is called ad hoc polymorphism, or method overloading
• In this case different methods within the same class or in a common hierarchy
share the same name but have different method signatures (name + parameters)
• public static float max(float a, float b)
• public static float max(float a, float b, float c)
• public static int max(int a, int b)
• When a method is called, the call signature is matched to the correct method
version
• Note: This is done during program COMPILATION
Method Overloading
• If an exact signature match is not possible, the one that is closest via “widening”
of the values is used
• “Widening” means that values of “smaller” types are cast into values of “larger”
types
• Ex: int to long int to float float to double
• Fewer widening provides a "closer" match
• If two or more versions of the method are possible with the same amount of
“widening”, the call is ambiguous, and a compilation error will result
static binding/Early Binding
• In Method Overloading method calls to the methods are decided by the
compiler iat compile time. Hence being EARLY BINDING.
• If there is any private, final or static method in a class, there is Early/static
binding.
• class Dog{
• private void eat(){
• System.out.println("dog is eating...");}
•
• public static void main(String args[]){
• Dog d1=new Dog();
• d1.eat();
• }
• }
Overriding
• A method defined in a superclass is redefined in a subclass with
an identical method signature
• Since the signatures are identical, rather than overloading the
method, it is instead overriding the method
– For subclass objects, the definition in the subclass replaces
the version in the superclass
Dynamic or Late Binding
• The code executed for a method call is associated with the call during run-
time
• The actual method executed is determined by the type of the object, not
the type of the reference
– Allows superclass and subclass objects to be accessed in a regular, consistent
way
• Array or collection of superclass references can be used to access a mixture
of superclass and subclass objects
• This is very useful if we want access collections of mixed data types (ex:
draw different graphical objects using the same draw() method call for
each)
Relations and Links
• Links and associations establish relationships among objects
and classes.
• Link:
– A connection between two object instances. A link is like a
tuple.
– A link is an instance of an association
• Association:
– Basically a bidirectional mapping.
– One-to-one, many-to-one, one-to-many,
– An association describes a set of links like a class describes
a set of objects.
Object Instance Diagram
Example for 1-to-N
:Item
Price:9,90
ItemID : 105
:Order
:Item
Price:105,00
ItemID : 98
:Item
Price:5,50
ItemID : 23
Many-to-Many Associations
places
**
Customer Order
Association
• the simplest form of relation between classes
• Association is one Class uses another Class
• It allows one object instance to cause another to perform an action on its
behalf.
public class StudentRegistrar {
public StudentRegistrar () {
new RecordManager().Initialize();
}
}
Aggregation
• a restrictive form of “part-of” association
• Class A contains Class B
• When object of one class has an (*has*) object of another,
• Life or existence of the aggregated objects are independent of each other
• Unlike association, aggregation always insists a direction.
• public class University {
• private Chancellor universityChancellor = new Chancellor();
• }
Composition
• a stricter form of aggregation
• Class A owns Class B.
• used where each part may belong to only one whole at a time.
• Life or existence of the composite object is dependent on the
existence of container object,
• Existence of composite object is not meaningful without its container
The Relationship
• aggregation is a special kind of an association and composition
is a special kind of an aggregation.
• (Association->Aggregation->Composition)
• If you are not even sure whether the relationship is best described as Association
or Composition or Aggregation, then model it as an Association.
Aggregation vs Inheritance
• Both associations describe trees (hierarchies)
• Aggregation tree describes “a-part-of “relationships (also called
and-relationship)
• Inheritance tree describes "kind-of" relationships (also called or-
relationship)
• Aggregation relates instances (involves two or more different
objects)
• Inheritance relates classes (a way to structure the description of
a single object)
Unified Modelling Language
UML
Modeling
• Modeling involves:
– representation or simplification of reality
– providing a blueprint of a system
• Used for better understanding of the system
• Describe the structure or behaviour of the system
• Experiment by exploring multiple solutions
• Document the design decisions
• Visualize the system “as-is” and ”to-be”
• Provide a template for constructing a system
Modeling Principles
• The choice of models affects how a problem is tackled
• Every model may be expressed at different levels of abstraction
• Effective models are connected to reality
• No single model is sufficient to describe non-trivial systems
What is UML?
• UML = Unified Modelling Language
• A language for visualizing, specifying, constructing and documenting
artifacts of software-intensive systems.
• Examples of artifacts: requirements, architecture, design,source code,
test cases, prototypes, etc.
• UML is suitable for modelling various kinds of systems:
– enterprise information systems,
– distributed web-based,
– real-time embedded system, etc.
UML – Specification Language
• Provides views for development and
deployment.
• UML is process-independent.
• UML is recommended for use with the
processes that are:
– use-case driven
– architecture-centric
– Iterative
– incremental
Goals of UML
• Provide modelers with an expressive, visual modelling language to
develop and exchange meaningful models
• Provide extensibility and specialization mechanisms to extend core
concepts
• Support specifications that are independent of particular
programming languages and development processes
• Provide a basis for understanding specification languages
• Encourage the growth of the object tools market
• Supports higher level of development with concepts such as
components frameworks or patterns
History of UML
• started as a unification of the Booch and Rumbaugh methods -
Unified Method v. 0.8 (1995)
• Jacobson contributes to produce UML 0.9, 1996
• UML Partners work with three Amigos to propose UML as a
standard modelling language to OMG in 1996.
• UML partners tender their proposal (UML 1.0) to OMG in 1997,
and 9 months later submit final UML 1.1.
• Minor revision is UML 1.4 adopted in May 2001, and the most
recent revision is UML 1.5, March 2003.
• UML 2.0 released by the end 2004.
UML Building Blocks
• Three basic building blocks:
– elements: main “citizens” of the model
– relationships: relationships that tie elements
together
– diagrams: mechanisms to group interesting
collections of elements and relationships
• Used to represent complex structures
Applications of UML
• UML is currently used for applications other than just
drawing designs
• Forward engineering
– UML model used to generate actual source code
• Reverse engineering
– UML models are generated from source code to re document or
recover design of program
Conceptual Elements
• static part of the model to represent conceptual
elements
• “nouns” of the model
1.Class
2.Interface
3.Collaboration
4.use case
5.active class
6.Component
7.node
Diagram
• A diagram is a graph presentation of a set of
elements and relationships where:
– nodes are elements
– edges are relationships
• Can visualize a system from various
perspective, thus is a projection of a system.
Diagram Types
• UML is characterized by nine major diagrams:
1.class
2.object
3.use case
4.sequence
5.collaboration
6.statechart
7. activity
8.Component
9.deployment
A Class
• A class is:
• a description of a set of objects that share the
same
– attributes,
– operations,
– relationships and
– semantics
• a software unit that implements one or more
interfaces
Class Diagrams
• the most widely used diagram of UML
• models the static design view of a system
• also useful in modelling business objects
• used to specify the structure, interfaces and
relationships between classes that underlie the system
architecture.
• primary diagram for generating codes from UML
models
Class Notation
• Basic notation: a solid-outline rectangle with
three compartments separated by horizontal
lines.
• Three compartments:
– top compartment holds the class name and other
general properties of the class
– middle compartment holds a list of attributes
– bottom compartment holds a list of operations
Class Diagram
Stereotypes for Classes
• Attribute or operation lists in a class may be organized into
groups with stereotypes.
• A number of stereotypes of classes and data types:
• thread
• event
• entity
• process
• utility
• Metaclass
• Powerclass
• enumeration, etc.
Attribute Syntax
Operations Syntax
Adding Visibility
• scope of access allowed to a member of a class
• applies to attributes and operations
• UML visibility maps to OO visibilities:
– private scope: within a class (-)
– package scope: within a package (~)
– public scope: within a system (+)
– protected scope: within an inheritance tree (#)
Identifying Classes
• Disparate Attributes and operations on a class :
– Split class so that each is part is coherent
• Difficulty in generalizing cleanly :
– one class may be playing two roles, spilt it up and page par may then
fit cleanly
• Duplication associations with same and purpose :
– generalize to create the missing super class that unites them
• Missing Access Path:
– Add New Associations so that you can answer the queries
• Lack of attributes ,operations and associations on a class
Candidates for classes• Tangible things referred to by common nouns in
requirements spec
– I.e., cookie, factory, triangle
• Events with associated information (i.e., flight,
game).
• Abstract data stores (i.e., buffer, tree, hash table)
• Note: verbs can also be classes!
– Parsing -> Parser, Scanner as a subclass of String
• Can anything be a class? What isn't a class?
– Proper nouns are instances of classes, not classes
– Classes have content: store state information and perform operations
– If it doesn’t store state and perform multiple operations, keep it simple
– Classes with just one or two routines (probably not worth classifying)
– Redundant classes: merge synonyms, reuse classes in libraries
Iterating Class Model
• A class model is can be created irately
• It can become correct after a single pass,
• different parts of a model are often at
different stages of completions
Adding Classes Example
• Candidate classes:
• Customer
• Order
• Inventory
Association
• Focus on those associations for which knowledge of
the relationship needs to be preserved for some
duration (“need-to-know”)
• It is more important to identify classes than to
identify associations
• Too many associations can be confusing
• Classes may have association with themselves
person
manages
1*
Construct Description Syntax
association a relationship between two or more
classifiers that involves connections
among their instances.
Multiplicity
Description Syntax
An A is always associated with one B
An A is always associate with one or
more B
An A is associated with zero or one B
An A is associated with zero, one or
more B
1
1..*
0..1
0..*
Generalization
• Generalization: identifying
commonality among classes
and defining supertype and
subtype relationships
Construct Description Syntax
generalization a taxonomic relationship between a
more general and a more specific
element.
Aggregation
Construct Description Syntax
composition
&
aggregation
A special form of association that
specifies a whole-part relationship
between the aggregate (whole) and
the component part.
• Composition (filled diamond):
 Strong ownership of one class (the part) by another (the whole)
 Exclusive relationship
• Aggregation (hollow diamond):
 Loose informal relationship. Indicates that the whole is more important
than the part
 Non-exclusive. The part may participate in other aggregations
Use Case Diagrams
• describe or capture functional requirements
• represent the desired behaviour of the system
• identify users (actors) of the system and associated
processes
• are the basic building blocks of use case diagrams
• tie requirements phase to other development phases
Use Case Diagrams
Use Case Definition
• A use case:
– is a collection of task-related activities describing a discrete chunk of
a system
– describes a set of actions sequences that a system performs to
present an observable result to an actor
• describes a system from an external usage viewpoint
• Key attributes of a use case:
– description
– action sequence
– includes variants
– produces observable results
Actor
• Definition
– Actor is anyone or anything that interacts with the system
causing it to respond to events
• An actor:
– is something or somebody that stimulates the system to
react or respond to its request
– is something we do not have control over
– represents a coherent set of roles that the external
entities to the system can play
– represents any type of a system’s user
Types of Actors
• Initiator versus participant:
– When there is more than one actor in a use case,
the one that generates the stimulus is called the
initiator and the others are participants.
• Primary versus secondary:
– The actor that directly interacts with the system is
called the primary actor, others are called
secondary actors.
Relationships
• Communication:
 Flow of data and control between an actor and use-case
• Uses:
 Use uses when you are repeating yourself in two or more separate
use cases and you want to avoid repetition
• Extends:
 Use extends when you are describing a carefully controlled
variation on normal behaviour
 Useful for identify core and extended functionality
 Needs to have extension points (specific aspects that are extended)
• Generalizes
 A casual description of a variation on normal behaviour
<<uses>>
<<uses>>
<<Extends>>
Identifying Use Cases
• Use cases describe:
– the functions that the user wants a system to
accomplish
– the operations that create, read, update, delete
information
– how actors are notified of the changes to the
internal state and how they notify the system
about external events
Identifying Actors
• To determine who are the actors,try to
answer the following questions:
– who uses the system?
– who gets information from the system?
– who provides information to the system?
– who installs, starts up or maintains the system?
Naming Use Cases
• Use concrete verb-noun phrases:
• a weak verb may indicate uncertainty, a strong
verb may clearly identify the action taken:
– strong verbs: create, calculate, migrate, activate, etc.
– weak verbs: make, report, use, organize, record, etc.
• a weak noun may refer to several objects, a
strong noun clearly identifies only one object
– strong nouns: property, payment, transcript, etc.
– weak nouns: data, paper, report, system, etc.
Naming Actors
• group individuals according to how they use the
system by identifying the roles they adopt while
using the system
• each role is a potential actor
• name each role and define its distinguishing
characteristics
• do not equate job titles with roles; roles cut
across jobs
• use common names for existing system; avoid
inventing new
E-Library – Use Case
Interaction Diagrams
• A model that describes how groups of objects
collaborate in some behaviour.
• Captures interaction in a single use case
• Works for a sequential process without
conditional or looping behaviour
• Two flavours:
 Sequence (emphasize the sequence of events)
 Collaboration (use layout to indicate how objects are statically connected)
Sequence Diagram
• A sequence diagram shows interactions between objects.
• Components of sequence diagrams:
• 1) object lifelines
– object
– timeline
• 2) messages
– message, stimulus
– signal, exception
– operations, returns
– identification
• 3) message syntax
Lifeline & Timeline
• The timeline is a line that runs:
– from the beginning of a scenario at the top of the diagram
– to the end of the scenario at the bottom of the diagram.
• An object lifeline consists of:
– an object
– a timeline
• If an object is created and destroyed during the message
sequence,
• the lifeline represents its whole lifecycle
Message
• Definition
– Message is a description of some type of communication between objects.
• A unit of communication between objects.
• The sender object may:
– invoke an operation,
– raise a signal or
– cause the creation or destruction of the target object.
Message Notation
• Notation: modeled as an arrow where the tail of the arrow identifies the
sender and the head points to the receiver.
• For each message we need to define:
– the name of the invoked operation and its parameters
–
– the information returned from the message
Synchronous Messages
• assumes that a return is needed
• sender waits for the return before proceeding with any other activity
• represented as a full arrow head
• return messages are dashed arrows
Asynchronous Messages
• does not wait for a return message
• exemplified by signals
• sender only responsible for getting the message to the
receiver
• usually modeled using a solid line and a half arrowhead to
distinguish it from the full arrowhead of the synchronous
message
Self-Reference Message
• A self-reference message is a message where the sender and receiver are
one and the same object.
• in a self-reference message the object refers to itself when it makes the
call
Notation
Construct Description Syntax
Deletion Indicates that an object has been
terminated

Asynchronous Message Message that does not block the
caller (which carries on with its
own processing)
Return Message Return from a previous message
(can be omitted)
Self-Call A message that an object sends
to itself
Sequence Diagram
SKILLWISE - OOPS CONCEPT

SKILLWISE - OOPS CONCEPT

  • 1.
  • 2.
    Core & AdvancedJava – Alpha Batch Unit- I OOPS Concepts
  • 3.
    Topics • OOP andits characteristics • OOP and its advantages • Understanding Classes and Objects • Encapsulation and Abstraction • Inheritance and Polymorphism • Object Interaction - Services/Methods/Functions • Object Relationship - Association, Aggregation and Composition • Understanding UML
  • 4.
    Structured Programming • Structuredprogramming – the data and the operations on the data are separate. • Data structures are created to hold attributes and is sent to functions to be operated on. • Link between functions and data is function parameter. • In an event of changes to Person , coder has to search for all places where data structure is being used and has to be modified. Public class Person { int id; String name; } public void add (Person p) {.....} public void remove (Person P) {.....}
  • 5.
    Object Oriented Programming •It has been around since 1967. • Popular programming paradigms in the mid-1980s . • In OOP data and operations are part of the same entity. • Closely models the real world, in which all objects have both attributes and code associated with them. • No need to pass in a reference to a Data structure as Methods implicitly know about the variables of their class and have full access to them. Public class Person { int id; String name; public void add() {.....} public void remove() {.....} }
  • 6.
    Structured Versus ObjectOriented Programming • Structured programming – Data lies separate from code. – No data abstraction or info hiding. – Programmer is responsible for organizing everything in to logical – units of code/data. – No help from compiler/language for enforcing modularity. • Object Oriented Programming – Model everything as objects. – Keep data near the relevant code. – Avoid reinventing the wheel. – Easier to understand, manage and maintain. – Simplify testing and debugging.
  • 7.
    Benefits of OOP •Promotes and facilitates software reuse. – Save development time and cost – Enables Easy Debugging – Classes can be tested independently – reused objects have already been tested • Facilitates interoperability • Results in software that is easy to modify, extend and maintain • Reduces integration effort • Some of the Popular OOP Languages – Simula,C++,SmartTalk,Java
  • 8.
    Features of OOP •Natural • Reliable • Reusable • Maintainable • Extendable • Timely
  • 9.
    Natural & Reliable •OOP produces natural software. Natural programs are more understandable. • Instead of programming in terms of an array or region of memory, programs uses the terminology of the particular problem. • Model a problem at a functional level, not at the implementation level • The modular nature of objects allows to make changes to one part of program without affecting other parts. • Objects isolate knowledge and responsibility where they belong. • One way to increase reliability is through thorough testing. • Isolation allows to test and validate each component independently. Once validated ,it can be reused
  • 10.
    Reusable & Maintainable •Objects can be reused in many different programs. ,inheritance allows to extend existing objects and polymorphism to write generic code. • OOP can model general ideas and use those general ideas to solve specific problems. • In order to fix a bug, simply correct the problem in one place. • Change to the implementation is transparent, all other objects will automatically benefit from the enhancement. • The natural language of the code should enable other developers to understand it as well.
  • 11.
    Timely & Extendable •A library of objects, extend your own objects’ functionality. • OOP aids these quick development cycles. OOP trims time off of the development cycle by providing reliable, reusable, and easily extendable software. • When you break down a program into a number of objects, the development of each piece can go on in parallel. • Multiple developers can work on classes independently. Such parallel development leads to quicker development times
  • 12.
    OOP Characteristics • Encapsulation- Enforces Modularity – Encapsulating the data and behavior into a single object is of primary importance in OO development. A single object contains both its data and behaviors and can hide what it wants from other objects. • Inheritance -Passes "Knowledge" Down – A class can inherit from another class and take advantage of the attributes and methods defined by the superclass. • Polymorphism -Takes any Shape – Polymorphism means that similar objects can respond to the same message in different manners. • Composition – Organizes objects – Composition means that an object is built from other objects.
  • 13.
    Encapsulation • It isthe ability of an object to place a boundary around its properties (data, methods). • It seals the data and methods safely inside the 'capsule' of a class, where it can be accessed only by trusted users (ie methods of the class). • While driving a car, user don't have to know the details of cylinders, ignition etc.
  • 14.
    Why Should Encapsulate •Reuse the object anywhere. • Upgrade component, by providing a more efficient implementation, or fix bugs—all without having to touch the other objects in your program. • The users of your object automatically benefit from any changes that you make. • Using an encapsulated object won’t cause unexpected side effects between the object and the rest of the program. Since the object is self- contained, • it won’t have any other interaction with the rest of the program beyond its interface.
  • 15.
    Abstraction Principle • Abstractionis the ability to focus on the important features of an object when trying to work with large amounts of information. • Example, – if we are trying to design a floor plan for a kitchen, we can focus on the shapes and relative sizes of the appliances and ignore attributes such as color,
  • 16.
    Effective Abstraction • Addressthe general case, not the specific case. • When confronting a number of different problems, search for commonality. Try to see a concept, not a specific case. • Abstraction might not be readily apparent. Abstraction might not jump out at you the first, second, or third time you solve a problem that is subject to being abstracted. • Prepare for failure. It is almost impossible to write an abstraction that will work in every situation.
  • 17.
    Inheritance • Inheritance isunique to OO – not there in function-oriented languages/models • Inheritance by class B from class A is the facility by which B implicitly gets the attributes and operations of A as part of itself • Attributes and methods of A are reused by B • When B inherits from A, B is the subclass or derived class and A is the base class or superclass
  • 18.
    Inheritance.. • A subclassB generally has a derived part (inherited from A) and an incremental part (is new) • Hence, B needs to define only the incremental part • Creates an “is-a” relationship – objects of type B are also objects of type A
  • 19.
  • 20.
    Inheritance… • The inheritancerelationship between classes forms a class hierarchy • In models, hierarchy should represent the natural relationships present in the problem domain • In a hierarchy, all the common features can be accumulated in a superclass • An existing class can be a specialization of an existing general class – is also called generalization-specialization relationships
  • 21.
    Inheritance… • Strict inheritance– a subclass takes all features of parent class • Only adds features to specialize it • Non-strict: when some of the features have been redefined • Strict inheritance supports “is-a” cleanly and has fewer side effects
  • 22.
    Inheritance… • Single inheritance– a subclass inherits from only one superclass • Class hierarchy is a tree • Multiple inheritance – a class inherits from more than one class • Can cause runtime conflicts • Repeated inheritance - a class inherits from a class but from two separate paths
  • 23.
    Diamond Problem When anobject of class D, any calls to method definitions in class A will be ambiguous – because it’s not sure whether to call the version of the method derived from class B or class C.
  • 24.
    Inheritance and Polymorphism •Inheritance brings polymorphism, i.e. an object can be of different types • An object of type B is also an object of type A • Hence an object has a static type and a dynamic type • Implications on type checking • Also brings dynamic binding of operations which allows writing of general code where operations do different things depending on the type
  • 25.
    Inclusion polymorphism • Itspure polymorphism, allows you to treat related objects generically. • Parametric polymorphism – allows to create generic methods and generic types,generic methods and types allow you to code something once and have it work with many different kinds of arguments. • Overriding – is an important type of polymorphism. • Overloading – also known as ad-hoc polymorphism, allows you to use the same method name for many different methods. Each method only differs in the number and type of its parameters.
  • 26.
    Method Overloading • Thisis called ad hoc polymorphism, or method overloading • In this case different methods within the same class or in a common hierarchy share the same name but have different method signatures (name + parameters) • public static float max(float a, float b) • public static float max(float a, float b, float c) • public static int max(int a, int b) • When a method is called, the call signature is matched to the correct method version • Note: This is done during program COMPILATION
  • 27.
    Method Overloading • Ifan exact signature match is not possible, the one that is closest via “widening” of the values is used • “Widening” means that values of “smaller” types are cast into values of “larger” types • Ex: int to long int to float float to double • Fewer widening provides a "closer" match • If two or more versions of the method are possible with the same amount of “widening”, the call is ambiguous, and a compilation error will result
  • 28.
    static binding/Early Binding •In Method Overloading method calls to the methods are decided by the compiler iat compile time. Hence being EARLY BINDING. • If there is any private, final or static method in a class, there is Early/static binding. • class Dog{ • private void eat(){ • System.out.println("dog is eating...");} • • public static void main(String args[]){ • Dog d1=new Dog(); • d1.eat(); • } • }
  • 29.
    Overriding • A methoddefined in a superclass is redefined in a subclass with an identical method signature • Since the signatures are identical, rather than overloading the method, it is instead overriding the method – For subclass objects, the definition in the subclass replaces the version in the superclass
  • 30.
    Dynamic or LateBinding • The code executed for a method call is associated with the call during run- time • The actual method executed is determined by the type of the object, not the type of the reference – Allows superclass and subclass objects to be accessed in a regular, consistent way • Array or collection of superclass references can be used to access a mixture of superclass and subclass objects • This is very useful if we want access collections of mixed data types (ex: draw different graphical objects using the same draw() method call for each)
  • 31.
    Relations and Links •Links and associations establish relationships among objects and classes. • Link: – A connection between two object instances. A link is like a tuple. – A link is an instance of an association • Association: – Basically a bidirectional mapping. – One-to-one, many-to-one, one-to-many, – An association describes a set of links like a class describes a set of objects.
  • 32.
    Object Instance Diagram Examplefor 1-to-N :Item Price:9,90 ItemID : 105 :Order :Item Price:105,00 ItemID : 98 :Item Price:5,50 ItemID : 23
  • 33.
  • 34.
    Association • the simplestform of relation between classes • Association is one Class uses another Class • It allows one object instance to cause another to perform an action on its behalf. public class StudentRegistrar { public StudentRegistrar () { new RecordManager().Initialize(); } }
  • 35.
    Aggregation • a restrictiveform of “part-of” association • Class A contains Class B • When object of one class has an (*has*) object of another, • Life or existence of the aggregated objects are independent of each other • Unlike association, aggregation always insists a direction. • public class University { • private Chancellor universityChancellor = new Chancellor(); • }
  • 36.
    Composition • a stricterform of aggregation • Class A owns Class B. • used where each part may belong to only one whole at a time. • Life or existence of the composite object is dependent on the existence of container object, • Existence of composite object is not meaningful without its container
  • 37.
    The Relationship • aggregationis a special kind of an association and composition is a special kind of an aggregation. • (Association->Aggregation->Composition) • If you are not even sure whether the relationship is best described as Association or Composition or Aggregation, then model it as an Association.
  • 38.
    Aggregation vs Inheritance •Both associations describe trees (hierarchies) • Aggregation tree describes “a-part-of “relationships (also called and-relationship) • Inheritance tree describes "kind-of" relationships (also called or- relationship) • Aggregation relates instances (involves two or more different objects) • Inheritance relates classes (a way to structure the description of a single object)
  • 39.
  • 40.
    Modeling • Modeling involves: –representation or simplification of reality – providing a blueprint of a system • Used for better understanding of the system • Describe the structure or behaviour of the system • Experiment by exploring multiple solutions • Document the design decisions • Visualize the system “as-is” and ”to-be” • Provide a template for constructing a system
  • 41.
    Modeling Principles • Thechoice of models affects how a problem is tackled • Every model may be expressed at different levels of abstraction • Effective models are connected to reality • No single model is sufficient to describe non-trivial systems
  • 42.
    What is UML? •UML = Unified Modelling Language • A language for visualizing, specifying, constructing and documenting artifacts of software-intensive systems. • Examples of artifacts: requirements, architecture, design,source code, test cases, prototypes, etc. • UML is suitable for modelling various kinds of systems: – enterprise information systems, – distributed web-based, – real-time embedded system, etc.
  • 43.
    UML – SpecificationLanguage • Provides views for development and deployment. • UML is process-independent. • UML is recommended for use with the processes that are: – use-case driven – architecture-centric – Iterative – incremental
  • 44.
    Goals of UML •Provide modelers with an expressive, visual modelling language to develop and exchange meaningful models • Provide extensibility and specialization mechanisms to extend core concepts • Support specifications that are independent of particular programming languages and development processes • Provide a basis for understanding specification languages • Encourage the growth of the object tools market • Supports higher level of development with concepts such as components frameworks or patterns
  • 45.
    History of UML •started as a unification of the Booch and Rumbaugh methods - Unified Method v. 0.8 (1995) • Jacobson contributes to produce UML 0.9, 1996 • UML Partners work with three Amigos to propose UML as a standard modelling language to OMG in 1996. • UML partners tender their proposal (UML 1.0) to OMG in 1997, and 9 months later submit final UML 1.1. • Minor revision is UML 1.4 adopted in May 2001, and the most recent revision is UML 1.5, March 2003. • UML 2.0 released by the end 2004.
  • 46.
    UML Building Blocks •Three basic building blocks: – elements: main “citizens” of the model – relationships: relationships that tie elements together – diagrams: mechanisms to group interesting collections of elements and relationships • Used to represent complex structures
  • 47.
    Applications of UML •UML is currently used for applications other than just drawing designs • Forward engineering – UML model used to generate actual source code • Reverse engineering – UML models are generated from source code to re document or recover design of program
  • 48.
    Conceptual Elements • staticpart of the model to represent conceptual elements • “nouns” of the model 1.Class 2.Interface 3.Collaboration 4.use case 5.active class 6.Component 7.node
  • 49.
    Diagram • A diagramis a graph presentation of a set of elements and relationships where: – nodes are elements – edges are relationships • Can visualize a system from various perspective, thus is a projection of a system.
  • 50.
    Diagram Types • UMLis characterized by nine major diagrams: 1.class 2.object 3.use case 4.sequence 5.collaboration 6.statechart 7. activity 8.Component 9.deployment
  • 51.
    A Class • Aclass is: • a description of a set of objects that share the same – attributes, – operations, – relationships and – semantics • a software unit that implements one or more interfaces
  • 52.
    Class Diagrams • themost widely used diagram of UML • models the static design view of a system • also useful in modelling business objects • used to specify the structure, interfaces and relationships between classes that underlie the system architecture. • primary diagram for generating codes from UML models
  • 53.
    Class Notation • Basicnotation: a solid-outline rectangle with three compartments separated by horizontal lines. • Three compartments: – top compartment holds the class name and other general properties of the class – middle compartment holds a list of attributes – bottom compartment holds a list of operations
  • 54.
  • 55.
    Stereotypes for Classes •Attribute or operation lists in a class may be organized into groups with stereotypes. • A number of stereotypes of classes and data types: • thread • event • entity • process • utility • Metaclass • Powerclass • enumeration, etc.
  • 56.
  • 57.
  • 58.
    Adding Visibility • scopeof access allowed to a member of a class • applies to attributes and operations • UML visibility maps to OO visibilities: – private scope: within a class (-) – package scope: within a package (~) – public scope: within a system (+) – protected scope: within an inheritance tree (#)
  • 59.
    Identifying Classes • DisparateAttributes and operations on a class : – Split class so that each is part is coherent • Difficulty in generalizing cleanly : – one class may be playing two roles, spilt it up and page par may then fit cleanly • Duplication associations with same and purpose : – generalize to create the missing super class that unites them • Missing Access Path: – Add New Associations so that you can answer the queries • Lack of attributes ,operations and associations on a class
  • 60.
    Candidates for classes•Tangible things referred to by common nouns in requirements spec – I.e., cookie, factory, triangle • Events with associated information (i.e., flight, game). • Abstract data stores (i.e., buffer, tree, hash table) • Note: verbs can also be classes! – Parsing -> Parser, Scanner as a subclass of String • Can anything be a class? What isn't a class? – Proper nouns are instances of classes, not classes – Classes have content: store state information and perform operations – If it doesn’t store state and perform multiple operations, keep it simple – Classes with just one or two routines (probably not worth classifying) – Redundant classes: merge synonyms, reuse classes in libraries
  • 61.
    Iterating Class Model •A class model is can be created irately • It can become correct after a single pass, • different parts of a model are often at different stages of completions
  • 62.
    Adding Classes Example •Candidate classes: • Customer • Order • Inventory
  • 63.
    Association • Focus onthose associations for which knowledge of the relationship needs to be preserved for some duration (“need-to-know”) • It is more important to identify classes than to identify associations • Too many associations can be confusing • Classes may have association with themselves person manages 1* Construct Description Syntax association a relationship between two or more classifiers that involves connections among their instances.
  • 64.
    Multiplicity Description Syntax An Ais always associated with one B An A is always associate with one or more B An A is associated with zero or one B An A is associated with zero, one or more B 1 1..* 0..1 0..*
  • 65.
    Generalization • Generalization: identifying commonalityamong classes and defining supertype and subtype relationships Construct Description Syntax generalization a taxonomic relationship between a more general and a more specific element.
  • 66.
    Aggregation Construct Description Syntax composition & aggregation Aspecial form of association that specifies a whole-part relationship between the aggregate (whole) and the component part. • Composition (filled diamond):  Strong ownership of one class (the part) by another (the whole)  Exclusive relationship • Aggregation (hollow diamond):  Loose informal relationship. Indicates that the whole is more important than the part  Non-exclusive. The part may participate in other aggregations
  • 67.
    Use Case Diagrams •describe or capture functional requirements • represent the desired behaviour of the system • identify users (actors) of the system and associated processes • are the basic building blocks of use case diagrams • tie requirements phase to other development phases
  • 68.
  • 69.
    Use Case Definition •A use case: – is a collection of task-related activities describing a discrete chunk of a system – describes a set of actions sequences that a system performs to present an observable result to an actor • describes a system from an external usage viewpoint • Key attributes of a use case: – description – action sequence – includes variants – produces observable results
  • 70.
    Actor • Definition – Actoris anyone or anything that interacts with the system causing it to respond to events • An actor: – is something or somebody that stimulates the system to react or respond to its request – is something we do not have control over – represents a coherent set of roles that the external entities to the system can play – represents any type of a system’s user
  • 71.
    Types of Actors •Initiator versus participant: – When there is more than one actor in a use case, the one that generates the stimulus is called the initiator and the others are participants. • Primary versus secondary: – The actor that directly interacts with the system is called the primary actor, others are called secondary actors.
  • 72.
    Relationships • Communication:  Flowof data and control between an actor and use-case • Uses:  Use uses when you are repeating yourself in two or more separate use cases and you want to avoid repetition • Extends:  Use extends when you are describing a carefully controlled variation on normal behaviour  Useful for identify core and extended functionality  Needs to have extension points (specific aspects that are extended) • Generalizes  A casual description of a variation on normal behaviour <<uses>> <<uses>> <<Extends>>
  • 73.
    Identifying Use Cases •Use cases describe: – the functions that the user wants a system to accomplish – the operations that create, read, update, delete information – how actors are notified of the changes to the internal state and how they notify the system about external events
  • 74.
    Identifying Actors • Todetermine who are the actors,try to answer the following questions: – who uses the system? – who gets information from the system? – who provides information to the system? – who installs, starts up or maintains the system?
  • 75.
    Naming Use Cases •Use concrete verb-noun phrases: • a weak verb may indicate uncertainty, a strong verb may clearly identify the action taken: – strong verbs: create, calculate, migrate, activate, etc. – weak verbs: make, report, use, organize, record, etc. • a weak noun may refer to several objects, a strong noun clearly identifies only one object – strong nouns: property, payment, transcript, etc. – weak nouns: data, paper, report, system, etc.
  • 76.
    Naming Actors • groupindividuals according to how they use the system by identifying the roles they adopt while using the system • each role is a potential actor • name each role and define its distinguishing characteristics • do not equate job titles with roles; roles cut across jobs • use common names for existing system; avoid inventing new
  • 77.
  • 78.
    Interaction Diagrams • Amodel that describes how groups of objects collaborate in some behaviour. • Captures interaction in a single use case • Works for a sequential process without conditional or looping behaviour • Two flavours:  Sequence (emphasize the sequence of events)  Collaboration (use layout to indicate how objects are statically connected)
  • 79.
    Sequence Diagram • Asequence diagram shows interactions between objects. • Components of sequence diagrams: • 1) object lifelines – object – timeline • 2) messages – message, stimulus – signal, exception – operations, returns – identification • 3) message syntax
  • 80.
    Lifeline & Timeline •The timeline is a line that runs: – from the beginning of a scenario at the top of the diagram – to the end of the scenario at the bottom of the diagram. • An object lifeline consists of: – an object – a timeline • If an object is created and destroyed during the message sequence, • the lifeline represents its whole lifecycle
  • 81.
    Message • Definition – Messageis a description of some type of communication between objects. • A unit of communication between objects. • The sender object may: – invoke an operation, – raise a signal or – cause the creation or destruction of the target object.
  • 82.
    Message Notation • Notation:modeled as an arrow where the tail of the arrow identifies the sender and the head points to the receiver. • For each message we need to define: – the name of the invoked operation and its parameters – – the information returned from the message
  • 83.
    Synchronous Messages • assumesthat a return is needed • sender waits for the return before proceeding with any other activity • represented as a full arrow head • return messages are dashed arrows
  • 84.
    Asynchronous Messages • doesnot wait for a return message • exemplified by signals • sender only responsible for getting the message to the receiver • usually modeled using a solid line and a half arrowhead to distinguish it from the full arrowhead of the synchronous message
  • 85.
    Self-Reference Message • Aself-reference message is a message where the sender and receiver are one and the same object. • in a self-reference message the object refers to itself when it makes the call
  • 86.
    Notation Construct Description Syntax DeletionIndicates that an object has been terminated  Asynchronous Message Message that does not block the caller (which carries on with its own processing) Return Message Return from a previous message (can be omitted) Self-Call A message that an object sends to itself
  • 87.