UNIT 2: Object-Oriented Analysis and Design (OOAD)
I. Fundamental Object-Oriented Concepts
Encapsulation
-
Definition: Bundling data (attributes) and methods (operations) that operate on the data into a single unit (class), while restricting direct access to some of the object's internal components.
-
Data Hiding: Using access specifiers (e.g.,
private,protected) to hide internal state, exposing only necessary interfaces. -
Role:
-
Modularity: Each class is a self-contained module.
-
Information Protection: Prevents external code from inadvertently corrupting an object's state.
-
-
Example: A
BankAccountclass with aprivate balanceattribute andpublic deposit()/withdraw()methods.
[!TIP] Exam Focus: Often asked with a simple example. Distinguish from abstraction (hiding complexity) vs encapsulation (bundling + access control).
Inheritance
-
Definition: Mechanism where a new class (subclass/child) derives properties and behaviors from an existing class (superclass/parent).
-
Types:
| Type | Description | Example | |------|-------------|---------| | Single | One subclass inherits from one superclass. |
Carinherits fromVehicle. | | Multiple | One subclass inherits from multiple superclasses. (Not supported in Java/C#) |FlyingCarinherits fromCarandAircraft. | | Multilevel | A chain of inheritance (A→B→C). |Vehicle→Car→SportsCar. | | Hierarchical | Multiple subclasses inherit from one superclass. |Car,Truckinherit fromVehicle. | | Hybrid | Combination of two or more types. |FlyingCar(Multiple) →Car(Hierarchical) →Vehicle. | -
Benefits:
-
Reuse: Avoids rewriting common code.
-
Extensibility: Easy to add new functionality.
-
-
Issues:
- Fragile Base Class Problem: Changes in superclass can break subclass behavior.
[!TIP] Common Pitfall: Confusing multiple inheritance (multiple parents) with multilevel (chain). Java uses interfaces to achieve multiple inheritance effects.
Polymorphism
-
Definition: Ability of an object to take many forms. The same interface can represent different underlying forms (data types).
-
Types:
-
Compile-Time (Static) Polymorphism:
-
Method Overloading: Multiple methods with same name but different parameters in same class.
-
Resolved at compile time.
-
-
Runtime (Dynamic) Polymorphism:
-
Method Overriding: Subclass provides a specific implementation of a method already defined in its superclass.
-
Dynamic Binding: Method call is resolved at runtime based on the actual object type.
-
-
-
Example:
class Animal { void sound() { System.out.println("Animal sound"); } } class Dog extends Animal { @Override void sound() { System.out.println("Bark"); } // Overriding } // Runtime: Animal a = new Dog(); a.sound(); // Outputs "Bark"
[!TIP] Key Distinction: Overloading = same method name, different parameters (compile-time). Overriding = same signature, different implementation (runtime).
Abstraction
-
Definition: Hiding implementation details and exposing only essential features of an object.
-
Mechanisms:
-
Abstract Classes: Cannot be instantiated; may contain abstract methods (no body) that subclasses must implement.
-
Interfaces: Pure abstraction; all methods are implicitly abstract (in Java 7-). A class can implement multiple interfaces.
-
-
When to Use:
-
Abstract Class: When sharing common code among closely related classes.
-
Interface: When defining a contract for unrelated classes or needing multiple inheritance of type.
-
[!TIP] Exam Question: "Difference between abstract class and interface" is frequent. Focus on multiple inheritance, default methods (Java 8+), and state (interfaces can't have instance variables).
II. UML and Object-Oriented Modeling
Class Diagrams
-
Purpose: Static structure diagram showing system's classes, attributes, operations, and relationships.
-
Elements:
-
Class Box: Three compartments:
-
Name (centered, bold)
-
Attributes (list:
visibility name : type) -
Operations (list:
visibility name (params) : return type)
-
-
Responsibilities: Often noted as textual notes; what the class is accountable for.
-
-
Relationships:
| Relationship | Symbol | Meaning | Example | |--------------|--------|---------|---------| | Association | Solid line | Structural relationship; "has-a". |
Student—Course| | Aggregation | Hollow diamond at aggregate end | Weak "whole-part"; part can exist independently. |Department◇—Professor| | Composition | Filled diamond | Strong "whole-part"; part lifecycle tied to whole. |Car◆—Engine| | Generalization | Hollow triangle arrow | Inheritance (subclass → superclass). |Dog△—Animal| | Dependency | Dashed arrow | Using relationship; change in supplier affects client. |Report..>Database| -
Multiplicity: Indicates how many objects participate in an association.
-
Notation:
1,0..1,1..*,*,0..* -
Example:
Customer"1" — "0..*"Order(One customer places zero or more orders).
-
-
Navigability: Arrowhead on association line indicates direction of traversal (e.g.,
A→Bmeans A knows about B, not necessarily vice versa).
[!TIP] Diagram Drawing: Always show multiplicity on both ends. Distinguish aggregation (hollow diamond) vs composition (filled diamond) by lifecycle dependency.
Example: Library System Class Diagram (Simplified)
[Book]
- ISBN: String
- title: String
+ checkout()
+ returnBook()
[Member]
- memberId: String
- name: String
+ borrowBook()
[Loan]
- loanDate: Date
- dueDate: Date
Relationships:
-
Member"1" — "0..*"Loan(Composition: Loan can't exist without Member?) -
Book"1" — "0..*"Loan(Association) -
Loan—Book(Navigable from Loan to Book)
Other UML Diagrams and Interrelationships
| Diagram | Purpose | Key Elements | Traceability |
|---|---|---|---|
| Use Case | Capture functional requirements. | Actors (stick figures), Use Cases (ovals), System boundary. Include (<<include>>), Extend (<<extend>>). |
Use Cases → Sequence/Collaboration diagrams (scenarios). |
| Sequence | Show object interactions over time. | Lifelines (vertical dashed), Synchronous (solid arrow) / Asynchronous (open arrow) messages, Activation bars. | Refines use case scenarios; shows method calls. |
| Collaboration | Similar to sequence but focuses on structural links. | Objects, Links, Messages. | Alternative to sequence; less time-focused. |
| State Chart | Model state-dependent behavior of a single class. | States (rounded rectangles), Transitions (arrows with event [guard] / action), Initial/Final states. |
Derived from class's dynamic behavior. |
| Activity | Model workflow or business process. | Actions (rounded rectangles), Transitions, Decision nodes (diamonds), Merge nodes, Swimlanes (partition by responsibility). | Can model use case flows or algorithm steps. |
| Component | Show physical software components (files, libraries). | Components (rectangle with tab), Interfaces (lollipop/socket). | Decomposition of system into modules. |
| Deployment | Show hardware topology and software deployment. | Nodes (3D boxes), Artifacts (files), Communication paths. | Maps components to physical nodes. |
How Diagrams Trace/Refine Each Other:
-
Requirements → Use Case Diagram: Identify actors and use cases.
-
Use Case → Sequence/Activity Diagrams: Detail scenarios and workflows.
-
Use Case → Class Diagram: Identify classes, attributes, operations from nouns/verbs.
-
Class Diagram → Sequence Diagrams: Show how classes collaborate to fulfill use cases.
-
Class Diagram → Component/Deployment: Map logical design to physical architecture.
Primary Goals of UML
-
Visualization: Standardized graphical notation for all stakeholders.
-
Specification: Precise, unambiguous system model.
-
Construction: Direct mapping to implementation (code generation).
-
Documentation: Artifacts for maintenance and knowledge transfer.
-
Communication: Common language among analysts, designers, developers, clients.
[!TIP] Exam Question: "Primary goals of UML" is direct. Remember the 4 S's: Specify, Visualize, Construct, Document.
III. Object-Oriented Design (OOD)
Definition and Process
-
Definition: Process of defining the architecture, components, interfaces, and characteristics of a system based on OO principles. It answers "How will the system be built?"
-
Transition from Analysis (OOA):
-
Analysis (What?): Understand problem domain, identify objects, their responsibilities, collaborations. Focus on requirements.
-
Design (How?): Define solution domain. Design classes, relationships, interfaces, algorithms, and system architecture. Focus on implementation feasibility.
-
-
Key Activities:
-
Design Classes: Refine analysis classes; add methods, define visibility.
-
Define Relationships: Establish associations, inheritance, dependencies.
-
Specify Interfaces: Define public contracts between subsystems.
-
Design System Architecture: Layering, subsystem decomposition.
-
Design Patterns: Apply reusable solutions (e.g., Singleton, Observer).
-
Translating OOD into Implementation
-
Mapping Design to Code:
| Design Element | Implementation (e.g., Java/C++) | |----------------|--------------------------------| | Class |
classkeyword | | Attribute | Instance variable | | Operation | Method | | Association | Reference/pointer variable; may need separate class for many-to-many | | Inheritance |extends(class),implements(interface) | | Interface |interfacekeyword | | Package/Subsystem |package(Java), namespace (C++) | -
Application of Design Patterns:
-
Singleton: Ensure one instance; provide global access point.
-
Observer: Define one-to-many dependency; notify observers of state changes.
-
Use patterns to solve recurring design problems.
-
-
Use of Tools & Round-Trip Engineering:
-
Code Generation: UML tools (e.g., Enterprise Architect, Rational Rose) generate skeleton code from diagrams.
-
Round-Trip Engineering: Synchronize model and code bidirectionally. Changes in code update model, and vice versa.
-
Managing Complexity in Large Systems
-
Modularity & Separation of Concerns:
-
Divide system into cohesive modules (classes, subsystems).
-
Each module has a single, well-defined responsibility (Single Responsibility Principle).
-
-
Reuse:
-
Inheritance: "Is-a" relationship; reuse via extension.
-
Composition: "Has-a" relationship; favor composition over inheritance for flexibility (avoid fragile base class).
- Example:
Carhas anEngine(composition) rather than being anEngine.
- Example:
-
-
Encapsulation:
-
Hide internal details behind interfaces.
-
Localizes Change: Modifying a class's internals doesn't affect clients if interface remains stable.
-
Reduces Coupling: Dependencies between modules are minimized.
-
[!TIP] Golden Rule: "Favor composition over inheritance" is a key design principle to avoid tight coupling and hierarchy brittleness.
IV. Object-Oriented Languages
Characteristics vs Procedural/Functional Languages
| Aspect | OO Languages | Procedural Languages (e.g., C) | Functional Languages (e.g., Haskell) |
|---|---|---|---|
| Primary Unit | Objects (data + behavior) | Procedures/Functions | Functions |
| Data & Code | Bundled (encapsulation) | Separate (global/local data) | Immutable data, pure functions |
| State | Encapsulated in objects | Often global/shared | Immutable; no side effects |
| Inheritance | Yes (reuse, polymorphism) | No | No (but type classes) |
| Polymorphism | Dynamic binding (runtime) | Limited (function overloading) | Parametric polymorphism |
| Invocation | Message Passing (object.method()) | Function calls | Function application |
| Abstraction | Abstract classes, interfaces | Header files, modules | Higher-order functions |
Fundamental Characteristics of OO Languages
-
Everything as Objects (except primitives in some):
intvsInteger. -
Classes as Primary Constructs: Blueprints for objects.
-
Support for Inheritance: Single/Multiple (language-dependent).
-
Support for Polymorphism: Overloading (compile-time), overriding (runtime).
-
Encapsulation: Access control mechanisms.
-
Dynamic Binding: Runtime resolution of method calls (via virtual tables in C++/Java).
-
Optional: Persistence (object serialization), Concurrency (threads).
[!TIP] Distinguish: Dynamic Binding (runtime method selection) vs Static Binding (compile-time). Essential for runtime polymorphism.
V. Object-Oriented Databases (OODB) and Query Languages
Query Languages for OODB (OQL)
-
OQL (Object Query Language): Standardized query language for OODBs (inspired by SQL but for objects).
-
Syntax & Features:
-
Similar to SQL
SELECTbut navigates object structures. -
Supports complex objects, inheritance, methods.
-
Navigational Access: Traverse object references directly.
-- Example: Find names of customers with savings account balance > 10000 SELECT c.name FROM Customers c WHERE c.accounts->balance > 10000 -- `c.accounts` is a collection; `->` navigates to each account's balance. -
-
Key Features:
-
Path Expressions:
object.attributeorobject.reference.attribute. -
Collection Types: Sets, lists, bags.
-
Inheritance Queries:
SELECT * FROM SubClassalso returns superclass attributes. -
Method Invocation: Can call methods in queries (e.g.,
c.getTotalBalance()).
-
Comparison: OQL vs SQL (Relational)
| Feature | OODB (OQL) | RDBMS (SQL) |
|---|---|---|
| Data Model | Objects (identity, state, behavior) | Tables (rows/columns) |
| Relationships | Direct object references (pointers) | Foreign keys + JOIN operations |
| Inheritance | Native support (subclass objects stored with superclass) | Workarounds: Single Table (discriminator), Class Table (multiple tables), Concrete Table. |
| Complex Data | Natural (nested objects, arrays) | Normalized (flat tables); complex types limited (JSON/XML columns). |
| Query Complexity | Simple for hierarchical/networked data (no joins). | Complex for deep hierarchies (multiple joins). |
| Performance | Efficient for object graphs (direct access). | Efficient for set-based operations; joins can be costly. |
| Impedance Mismatch | None: Objects map directly to storage. | Exists: Need ORM (Object-Relational Mapping) to convert objects to tables. |
[!TIP] Exam Focus: "How does OODB query language differ from SQL?" – Highlight navigational access vs joins, native inheritance, and impedance mismatch.
Final Notes for Exam:
-
Draw diagrams clearly: Class diagrams with proper multiplicity, diamonds for aggregation/composition.
-
Use examples: Relate concepts to real systems (Library, Banking).
-
Definitions first: Start answers with crisp definitions (e.g., "Encapsulation is...").
-
Contrast: Always compare OO vs procedural when asked.
-
UML Goals: Memorize the 4 primary goals (Specify, Visualize, Construct, Document).