π Lecture 01 β Object Oriented Programming (CS304)
π Overview: This lecture introduces the fundamental concepts of object-oriented programming (OOP) and object-orientation as a technique for visualizing and solving programming problems. It explains why OOP maps naturally to real-world scenarios, making it easier to develop, understand, and implement complex systems.
ποΈ Topics Covered
This lecture covers the introduction to object-orientation, what a model is and why we need models, how object-oriented models represent real-world systems through interacting objects, the advantages of object-orientation, the definition and properties of objects, and the distinction between tangible and intangible objects with examples.
π Lecture Summary
01.1. Introduction
Course Objective: The objective of this course is to make students familiar with the concepts of object oriented programming. These concepts will be reinforced by their implementation in C++.
Course Contents: The main topics covered across 45 lectures are: Object Orientation, Objects and Classes, Overloading, Inheritance, Polymorphism, Generic Programming, Exception Handling, and Introduction to Design Patterns.
Recommended Text Book: C++ How to Program by Deitel & Deitel. Reference books include Object-Oriented Software Engineering by Jacobson et al. and The C++ Programming Language by Bjarne Stroustrup.
What is Object-Orientation? It is a technique in which we visualize our programming problems in the form of objects and their interactions, as happens in real life. Examples include a person, a house, a tree, and a car β objects that interact with each other to perform different operations (e.g., a person lives in a house, a person drives a car). In a school, objects include students, teachers, books, pens, school bags, classrooms, parents, and playgrounds. To develop a fee collection system for a school, we find related objects and their interactions as in real life.
In object orientation, we move concentration to objects in contrast to the procedural paradigm where we simply write code in functions and call them in the main program.
01.2. What is a Model?
A model is an abstraction of something real or conceptual. We need models to understand an aspect of reality. Model examples include highway maps, architectural models, and mechanical models.
01.3. OO Models
In the context of programming, models are used to understand the problem before starting development. We make Object Oriented models showing several interacting objects to understand a system given for implementation.
Example 1 β Object Oriented Model: Objects: Ali, Car, House, Tree. Interactions: Ali lives in the house, Ali drives the car.
Example 2 β Object Oriented Model (A School Model): Objects: Teacher, Student, School Bag, Pen, Book, Playground. Interactions: Teacher teaches Student, Student has School Bag, Book, and Pen.
01.4. Object-Orientation - Advantages
As Object Oriented Models map directly to reality, we can easily develop an OO model for a problem, everyone can easily understand an OO model, and we can easily implement an OO model using any object oriented language like C++ with features such as classes, inheritance, and virtual functions.
01.5. What is an Object?
An object is:
- Something tangible (Ali, School, House, Car)
- Something conceptual (that can be apprehended intellectually, e.g., time, date)
An object has:
- State (attributes)
- Well-defined behavior (operations)
- Unique identity
01.6. Tangible and Intangible Objects
Examples of Tangible Objects: Ali is a tangible object with characteristics (attributes): Name, Age; and behavior (operations): Walks, Eats. We identify Ali using his name. A Car has state (attributes): Color, Model; behavior (operations): Accelerate, Start Car, Change Gear. We identify a car using its registration number.
Examples of Intangible Objects (Conceptual Objects): Time is an intangible object with state: Hours, Seconds, Minutes; behavior: Set/Get Hours, Set/Get Seconds, Set/Get Minutes. We assign an own generated unique ID in the model for a Time object. Date is an intangible object with state: Year, Day, Month; behavior: Set/Get Year, Set/Get Day, Set/Get Month. We assign an own generated unique ID for a Date object.
β Key Takeaways
The most critical concepts to remember are: object-orientation visualizes programming problems as interacting real-world objects, making problem-solving more intuitive than the procedural paradigm. A model is an abstraction used to understand reality before implementation. Every object has three essential properties: state (attributes/data), behavior (operations/functions), and unique identity. Objects can be tangible (physical like a car or person) or intangible/conceptual (like time or date). Nouns in a problem description are candidates for becoming objects in the system, and object-oriented models map directly to reality, enabling easier understanding and implementation.
π§ Quick Revision Questions
- What is the fundamental difference between the object-oriented paradigm and the procedural paradigm?
- What are the three essential properties that every object must have?
- Give two examples each of tangible objects and intangible (conceptual) objects in the context of OOP.
- Why are models important in object-oriented programming? What do they help us achieve?
- What is meant by "nouns in a problem description are candidates for becoming objects"? Provide an example.
π Lecture 02 β Information Hiding, Encapsulation, Interface, Implementation, Separation of Interface & Implementation, Messages
π Overview: This lecture explores foundational OOP principles that govern how objects manage and expose their data and behavior. It explains how information hiding and encapsulation protect an object's internal state, and how interfaces provide controlled access to that state, while implementation remains hidden. This separation is crucial for building modular, maintainable, and secure object-oriented systems.
ποΈ Topics Covered
The lecture covers Information Hiding as the core principle of restricting access to object details, followed by Encapsulation which bundles data and behavior together. It then defines Interface as the set of exposed functions, and Implementation as the hidden internal data structures and functionality. The Separation of Interface & Implementation is discussed as a key design goal, and finally, Messages are introduced as the mechanism for object communication.
π Lecture Summary
02.1. Information Hiding
This is a core OOP principle inspired by real life: not all information should be accessible to everyone. In OOP, it means hiding an objectβs details (its state and behavior) from other objects or users (where "users" means other objects or external programs). Information hiding simplifies the model by focusing only on object interactions, not internal workings. It also acts as a barrier against change propagation because changing the internal implementation of a function does not affect other parts of the system that only use the function's name and parameters.
π Definition β Information Hiding: "Showing only those details to the outside world which are necessary for the outside world and hiding all other details from the outside world."
π‘ Why this matters: This principle prevents accidental or malicious interference with an object's internal state, making code more robust and secure. It also allows developers to change internal logic without breaking other parts of the program.
Examples:
- A person named Ali keeps his personal information in his brain; we must ask him for it, and he controls how much to share.
- An email server has millions of accounts but only shares our account with us when we request it.
- A phone SIM card stores phone numbers, but the phone-set reads them for us; the owner can restrict access to those numbers.
Achieving Information Hiding:
- All information related to an object is stored within the object.
- It is hidden from the outside world.
- It can only be manipulated by the object itself.
02.2. Encapsulation
Encapsulation is the mechanism that bundles an object's data members (state) and functions (behavior) together within the object. It is closely related to information hiding, as encapsulation is the primary way to achieve it. The data and behavior are tightly coupled inside the object, and both the information structure and the implementation details of its operations are hidden from the outside world.
Advantages of Encapsulation:
- Simplicity and clarity: All data and functions are stored within objects, eliminating free-floating code.
- Low complexity: Functions are not chaotically intertwined; each object has a specific, contained behavior.
- Better understanding: Object diagrams are self-explanatory as each object has a specific role and relations.
Examples:
- The object
Aliencapsulates his personal information (like his name and age) and his behaviors (like walking and eating). Another object cannot use his behavior without Aliβs permission. - A phone encapsulates its stored data (contacts, etc.) and the behavior to show that data; we can only access it through the phone's interface.
π Definition β Encapsulation: "We have enclosed all the characteristics of an object in the object itself."
02.3. Interface
An objectβs interface is the set of functions it chooses to expose to other objects. Since data and behavior are hidden, the interface provides the only means for external objects to interact with it. Different objects may need different functions, so an interface can be different for different requesting objects. Interfaces are necessary for object communication.
Examples:
- Interface of a Car: Steer Wheels, Accelerate, Change Gear, Apply Brakes, Turn Lights On/Off.
- Interface of a Phone: Input Number, Place Call, Disconnect Call, Add number to address book, Remove number, Update number.
π Definition β Interface: A set of functions of an object that it wants to expose to other objects.
02.4. Implementation
Implementation is the actual, hidden code and data structures that realize the behavior defined by the interface. It has two main parts:
- Internal data structures: These hold the object's state (the actual values of data members).
- Functionality: This is provided by the member functions that define the object's behavior.
Examples:
- Gear Box in a car system: The implementation includes the mechanical structure of the gear box (its data structure) and the mechanism to change gear (its functionality).
- Address Book in a Phone: The physical structure of the SIM card acts as the data structure, and the phone's read/write operations provide the functionality.
π Definition β Implementation: The actual implementation of the behavior of the object in any Object Oriented language, consisting of internal data structures and functionality.
02.5. Separation of Interface & Implementation
This principle states that we should only show the interface of an object to the outside world and hide the implementation. This makes the interface independent of its internal implementation. This is achieved through encapsulation and information hiding.
Real Life Example: A driver uses a standard interface (steering wheel, pedals, gear shift) to drive a car. Using this interface, they can drive any car, regardless of its engine type, fuel type, or specific model, because the interface is separate from the implementation.
π‘ Why this matters: This separation allows developers to change the internal implementation of an object (e.g., improving a sorting algorithm or changing a data structure) without changing any code that uses that object, as long as the interface remains unchanged.
02.6. Messages
Objects communicate by sending messages (also called stimuli) to each other. A message is sent by invoking an appropriate operation on the target object. The number and kind of messages that can be sent to an object are determined by its interface.
Examples- Messages:
- A Person sends a "stop" message to a Car by applying the brakes.
- A Person sends a "place call" message to a Phone by pressing the appropriate button.
π Definition β Messages: The mechanism by which objects communicate, sent by invoking an operation on the target object.
β Key Takeaways
This lecture establishes that objects are self-contained units that hide their internal details (encapsulation and information hiding) and only expose a carefully selected set of operations (interface). The implementation of those operations and the internal data structures are completely separate from the interface, a principle known as separation of interface and implementation. Objects interact not by directly accessing each other's data, but by sending messages that trigger specific behaviors through the interface. These principles are fundamental for building modular, robust, and maintainable software systems.
π§ Quick Revision Questions
- What is the difference between information hiding and encapsulation as described in this lecture? How are they related?
- Explain the concept of an interface and provide two distinct real-world examples of an object's interface, other than a car or phone.
- What are the two main parts of an object's implementation? Give an example for each.
- Why is the separation of interface and implementation considered a good design principle? What practical benefit does it provide to a developer?
- What is a message in OOP? Using the car example, describe how a driver would send a message to the car and what operation that message invokes.
π Lecture 03 β Abstraction, Classes, Inheritance
π Overview: This lecture introduces three foundational concepts of Object-Oriented Programming. It explains how abstraction simplifies real-world complexity, how classes serve as blueprints for creating objects, and how inheritance enables code reuse through hierarchical relationships between classes. Understanding these concepts is essential for designing efficient, maintainable, OOP-based systems.
ποΈ Topics Covered
The lecture covers Abstraction as a principle for focusing only on relevant details of objects, using an example of a person who is both a student and a teacher. It then introduces Classes as prototypes or sketches for creating object instances, with examples like Student, Teacher, and Circle classes. Finally, Inheritance is explained as an "IS A" relationship where derived classes inherit characteristics from base classes, with major benefits including Reuse, reduced redundancy, and increased maintainability.
π Lecture Summary
Abstraction
Real-life objects have many attributes and behaviors, but most of the time we are only interested in the part relevant to the current problem. For example, when implementing a school system, we don't need to care about the personal life of a student or teacher, as it won't affect the system. This concept is called "Abstraction." Abstraction is a way to cope with complexity and is used to simplify things.
π Definition β Abstraction: "Capture only those details about an object that are relevant to current perspective."
π Example: For the statement "Ali is a PhD student and teaches BS students":
- From the student perspective: attributes like Name, Student Roll No, Year of Study, CGPA, Age; behaviors like Study, GiveExam, PlaySports
- From the teacher perspective: attributes like Name, Employee ID, Designation, Salary, Age; behaviors like DevelopExam, TakeExam, DeliverLecture, Walk
- Many attributes (like Name, Age) are common to both perspectives, but others are specific to one role.
Abstraction has major advantages:
- It helps in understanding and solving a problem using OOP by hiding extra irrelevant details.
- Focusing on a single perspective provides freedom to change implementation for other aspects later.
π‘ Why this matters: Similar to encapsulation, abstraction achieves information hiding β showing only relevant details to related objects and hiding other details.
Classes
In OOP, we create a general sketch for each kind of object, then create different instances using this sketch. This sketch, prototype, or map is called a "class." All objects of the same kind exhibit identical characteristics (information structure and behavior), though they have data of their own.
π Definition β Class: A blueprint or prototype that defines the attributes and behaviors for a kind of object. Objects are instances of a class.
π Example 1 β Student Class: Ali studies mathematics, Anam studies physics, Sohail studies chemistry. Each is a student β they are instances of the Student class.
π Example 2 β Teacher Class: Ahsan teaches mathematics, Aamir teaches computer science, Atif teaches physics. Each is a teacher β they are instances of the Teacher class.
Class Representation: A class can be represented as a rectangle with three compartments:
- Normal Form: Shows Class Name (top), Attributes (middle), Operations/behaviors (bottom) β e.g.,
Circlewith attributescenter,radiusand operationsdraw,computeArea - Suppressed Form: Shows only the Class Name β e.g., just
Circle
Inheritance
A child inherits characteristics of its parents. Besides inherited characteristics, a child may have its own unique characteristics.
Inheritance in Classes: If a class B inherits from class A, then B contains all the characteristics (information structure and behavior) of class A. The parent class is called the base class and the child class is called the derived class. Besides inherited characteristics, a derived class may have its own unique characteristics.
π Definition β Inheritance: "IS A" or "IS A KIND OF" relationship between classes. For example: Student IS A Person, Teacher IS A Person, Doctor IS A Person. Similarly, Circle IS A Shape, Line IS A Shape, Triangle IS A Shape.
π Example β Person Hierarchy:
- Base class
Person: attributesname,age,gender; behaviorseat,walk - Derived class
Student: adds attributesprogram,studyYear; behaviorsstudy,heldExam - Derived class
Teacher: adds attributesdesignation,salary; behaviorsteach,takeExam - Derived class
Doctor: adds attributesdesignation,salary; behaviorscheckUp,prescribe
π Example β Shape Hierarchy:
- Base class
Shape: attributescolor,coord; behaviorsdraw,rotate,setColor - Derived class
Circle: adds attributeradius; behaviorsdraw,computeArea - Derived class
Line: adds attributelength; behaviordraw - Derived class
Triangle: adds attributeangle; behaviorsdraw,computeArea
Inheritance β Advantages:
- Reuse β Main purpose of inheritance is reuse; we can easily add new classes by inheriting from existing ones.
- Less redundancy β Common code is written once in the base class.
- Increased maintainability β Changes to the base class automatically propagate to derived classes.
π‘ Why this matters: With reuse, you select an existing class closer to the desired functionality, create a new class, inherit it from the selected class, then add to and/or modify the inherited functionality.
β Key Takeaways
Abstraction is the OOP principle of capturing only relevant details of an object for a given perspective, hiding complexity. Classes act as blueprints or prototypes from which objects (instances) are created; all instances share the same structure and behavior but have their own data. Inheritance creates an "IS A" relationship where a derived class inherits all characteristics from a base class while adding its own unique features. The major benefits of inheritance are reuse, reduced redundancy, and increased maintainability. For the exam, remember that class diagrams use a rectangle with three compartments (name, attributes, operations), with normal and suppressed forms.
π§ Quick Revision Questions
- What is abstraction, and why is it important in object-oriented programming?
- How does a class differ from an object? Provide an example for each.
- Explain the "IS A" relationship with respect to inheritance using the Shape hierarchy.
- List and explain the three major advantages of inheritance.
- In the Ali example, which attributes belong only to the student perspective and which only to the teacher perspective?
π Lecture 04 β Lecture No.04
π Overview: This lecture explores advanced inheritance concepts in Object-Oriented Programming, focusing on how classes relate to each other beyond simple parent-child relationships. It introduces generalization, subtyping, specialization, overriding, and the crucial distinction between abstract and concrete classes, which are fundamental for designing flexible and reusable software systems.
ποΈ Topics Covered
The lecture covers concepts related to inheritance including generalization (extracting common features into a base class), subtyping/extension (where derived class is behaviourally compatible with base), specialization/restriction (where derived class is behaviourally incompatible), overriding (redefining base class behaviour), and the difference between abstract classes (cannot be instantiated) and concrete classes (can be instantiated).
π Lecture Summary
04.1. Concepts Related with Inheritance
The lecture introduces three key inheritance concepts: Generalization, Subtyping (extension), and Specialization (restriction). These concepts describe different ways derived classes relate to their base classes.
04.2. Generalization
In OO models, some classes may have common characteristics. We extract these features into a new class and inherit original classes from this new class. The Base class encapsulates the idea of commonality of derived classes. This concept is known as Generalization. It reduces redundancy and gives us reusability; using generalization our solution becomes less complex. In generalization there should be βIs a Kind of Relationshipβ (also called βIs A relationshipβ) between base and child classes.
Example: Line, Circle and Triangle all share common attributes (color, vertices) and common behaviour (move, setColor). These are extracted into a general Shape class.
Example: Student, Doctor and Teacher all share common attributes (name, age, gender) and common behaviour (eat, walk). These are extracted into a general Person class.
04.3. Sub-typing (Extension)
Sub-typing means that derived class is behaviourally compatible with the base class. Derived class has all the characteristics of base class plus some extra characteristics. Behaviourally compatible means that base class can be replaced by the derived class.
Example: Circle is extending the behaviour of Shape by adding radius and methods like computeCircumference and computeArea. Student has two extra attributes (program, studyYear) and extended behaviour (study, takeExam).
Subtyping and generalization are related concepts. Subtyping (extension) and generalization is a way to look at the same thing in two ways. Sub typing is looking at things from Top to bottom whereas in generalization we look at things from bottom to top.
04.4. Specialization (Restriction)
We want to add a class to existing hierarchy of classes having many similarities to already existing classes but some part of its behaviour is different or restricted. In that case we will use the concept of Specialization. Specialization means that derived class is behaviourally incompatible with the base class. Behaviourally incompatibility means that base class canβt always be replaced by the derived class. Derived class has some different or restricted characteristics than of base class.
Example β Specialization (Restriction): Suppose we want to add a class of Adult for ID card generation such that it is a person but its age is greater than 18. Rather than writing all code again, we derive Adult class from Person class and restrict age in that class.
- Person: age : [0..100]
- Adult: age : [18..100] with setAge method restricted to accept only ages >= 18
Example: Natural Numbers are also Integers with the restriction that natural numbers set can NOT contain zero or negative integers. NaturalSet inherits from IntegerSet but restricts the add method.
- IntegerSet: add(elem) - adds element to set
- NaturalSet: add(elem) - if elem < 1 then error, else add element to set
π‘ Why this matters: Add method behaviour is present in both base and derived classes but derived class behaviour is different. Derived class will not exhibit the behaviour of base class but it is overriding behaviour of base class with its own behaviour.
04.5. Overriding
A class may need to override the default behaviour provided by its base class. Derived class overrides the behaviour of its base class.
Reasons for overriding:
- Provide behaviour specific to a derived class (specialization)
- Extend the default behaviour (extension)
- Restrict the default behaviour (restriction)
- Improve performance
Example β Specific Behaviour (Specialization): Shape has a draw method. Circle, Line, and Triangle each override draw with their own specific drawing implementation.
Example β Extension: IntegerSet has add method to add element to set. NaturalSet overrides add with if elem < 1 then give error, else add element to the set.
Example β Extension: Window has draw method. DialogBox overrides draw to first invoke Window's draw, then draw the dialog box.
Example β Restriction: NaturalSet restricts the add method of IntegerSet.
Example β Improve Performance: Class Circle overrides rotate operation of class Shape with a Null operation (doing nothing).
04.6. Abstract Classes
In our examples we made classes for Shape and Person. These are abstract concepts and the classes we make against abstract concepts are called Abstract Classes. They are present at or near the top in the class hierarchy to present most generalized behaviour.
An abstract class:
- Implements an abstract concept
- Main purpose is to be inherited by other classes
- Canβt be instantiated
- Promotes reuse
Abstract Classes - Example I: Shape (abstract class) β Circle, Line, Triangle (concrete classes)
Abstract Classes - Example II: Person (abstract class) β Student, Teacher, Doctor, Engineer, Director (concrete classes)
Abstract Classes - Example III: Vehicle (abstract class) β Car, Bus, Truck (concrete classes)
Abstract Classes cannot exist standalone in an object model. While making object model we start by finding out objects in our object model and then we find out objects having common attributes and make them in the form of general classes at the top of class hierarchies.
04.7. Concrete Classes
The entities that actually we see in our real world are called concrete objects and classes made against these objects are called Concrete Classes.
A concrete class:
- Implements a concrete concept
- These are used to instantiate objects in our programs
- Provides implementation details specific to the domain context
Concrete Classes - Example I: Student, Teacher and Doctor are concrete classes derived from Person.
Concrete Classes - Example II: Car, Bus and Truck are concrete classes derived from Vehicle.
- A concrete class may exist in an object model independently
- Concrete classes mostly lie below the top of class hierarchy in a good object model
If there is an abstract class then hierarchy exists in the object model as there will definitely be some concrete classes as well derived from this abstract class otherwise there is no use of abstract class.
β Key Takeaways
Generalization extracts common features from multiple classes into a base class to reduce redundancy and promote reuse, while subtyping (extension) adds new features and specialization (restriction) modifies or limits inherited behaviour. Overriding allows derived classes to replace base class behaviour for reasons including specialization, extension, restriction, or performance improvement. Abstract classes represent generalized concepts that cannot be instantiated but must be inherited, while concrete classes represent real-world entities that can be instantiated. The key exam concept is understanding that subtyping views relationships top-down while generalization views them bottom-up.
π§ Quick Revision Questions
- What are the three main concepts related with inheritance discussed in this lecture?
- How does generalization differ from subtyping in terms of direction (top-down vs bottom-up)?
- What does it mean for a derived class to be "behaviourally compatible" with its base class?
- Give two reasons why a derived class might override a method from its base class.
- What is the main difference between an abstract class and a concrete class?
π Lecture 05 β Multiple Inheritance
π Overview: This lecture introduces multiple inheritance, where a class inherits from more than one parent class. It covers its advantages, such as code reuse, and its significant disadvantages, including increased complexity and the diamond problem, while also shifting focus to association relationships between objects.
ποΈ Topics Covered
The lecture begins by revisiting the purposes of inheritance from the last lecture, then formally introduces multiple inheritance with examples (Mermaid, Amphibious Vehicle) and its C++ syntax. It details the problems associated with multiple inheritance, specifically ambiguity and the diamond problem, and provides solutions like overriding and virtual inheritance. The second half defines association and its two main types: class association (implemented via inheritance) and object association, which includes simple association, composition, and aggregation, along with their properties and UML notation.
π Lecture Summary
05.1. Multiple Inheritance
Multiple Inheritance is a feature where a derived class inherits from more than one base class. This allows the derived class to reuse characteristics of multiple parent classes.
π Definition β Multiple Inheritance: The ability of a class to inherit attributes and methods from more than one base class.
π Example 1: The Mermaid class inherits from both Woman and Fish classes, gaining the ability to walk() and swim().
π Example 2: The AmphibiousVehicle class inherits from both LandVehicle and WaterVehicle classes, gaining the Move() and Float() methods.
Problems with Multiple Inheritance
While multiple inheritance reduces code redundancy, it introduces several problems.
- Increased Complexity: The class hierarchy becomes more complicated and less understandable.
- Reduced Understanding: The object model is difficult to understand for someone seeing it for the first time.
- Duplicate Features: Features (same method name) may appear in multiple parent classes.
Problem 1: Ambiguity
When both parent classes have a method with the same name, the compiler cannot determine which one to inherit. For example, if both Woman and Fish have an eat() method, from which class should Mermaid inherit it?
π Definition β Ambiguity: A situation where a derived class has multiple potential definitions for an inherited member, leading to a compile-time error.
β
Solution: Override the ambiguous method in the derived class and explicitly call the desired base class method using the scope resolution operator (e.g., Woman::eat()).
Problem 2: Two Instances for Same Function (Diamond Problem)
This occurs in a "diamond" hierarchy where a class inherits from two classes that both inherit from a common base class. For example, AmphibiousVehicle inherits from LandVehicle and WaterVehicle, which both inherit from Vehicle. This results in two copies of the Vehicle class within the AmphibiousVehicle object, causing ambiguity for inherited members like changeGear().
π Formula: Diamond Problem: A β (B, C) β D, where both B and C inherit from A, and D inherits from both B and C. This creates two instances of A's members in D.
β Solution: The problem is solved through virtual inheritance, which ensures only one copy of the common base class is included in the derived class. Some languages also simply disallow diamond hierarchies.
05.2. Kinds of Association
Association describes the interaction of different objects in an object-oriented model.
π Definition β Association: A relationship between two or more objects that defines how they interact with each other to perform work.
1. Class Association
This is implemented via Inheritance. It represents a relationship between classes.
- Public Inheritance: An "IS-A" relationship.
- Private Inheritance: An "Implemented in terms of" relationship.
2. Object Association
This is the interaction between stand-alone objects of different classes. It has three main types: Simple Association, Composition, and Aggregation.
05.3. Simple Association
The weakest link between two objects that have no intrinsic relationship with each other. It is a reference by which one object can interact with another (e.g., Ali drives a Car).
π Definition β Simple Association: A relationship where two objects interact but have no ownership or part-whole relationship.
Kinds of Simple Association w.r.t Navigation:
- One-way Association: Navigation is possible in only one direction, denoted by an arrow (
β). - Two-way Association: Navigation is possible in both directions, denoted by a simple line (
β).
Kinds of Simple Association w.r.t Cardinality:
- Binary Association: Associates objects of exactly two classes.
- Ternary Association: Associates objects of exactly three classes, denoted by a diamond with lines.
- N-ary Association: An association between 3 or more classes.
05.4. Composition
A strong "part-of" relationship where the composed object is a part of the whole and cannot exist independently.
π Definition β Composition: A strong form of association where an object is composed of other objects, and the "part" objects cannot exist independently of the "whole" object (e.g., Ali is composed of Head, Arm, etc.). Represented by a line with a filled-diamond head towards the composer.
π‘ Why this matters: The lifetime of the "part" is tied to the lifetime of the "whole." If the whole is destroyed, the parts are also destroyed.
05.5. Aggregation
A weaker "has-a" relationship where the container object holds a collection of other objects that can exist independently.
π Definition β Aggregation: A form of association where an object contains a collection of other objects, but the contained objects can exist independently of the container (e.g., A Room contains Furniture). Represented by a line with an unfilled-diamond head towards the container.
π‘ Why this matters: The container does not own the lifecycle of the contained objects. The contained objects can exist and be part of other containers.
β Key Takeaways
The lecture is split into two core concepts: the mechanics and pitfalls of multiple inheritance, and the various types of association between objects. For multiple inheritance, remember that while it allows powerful code reuse, it introduces ambiguity and the diamond problem, which require explicit solutions like overriding or virtual inheritance. For associations, you must distinguish between class association (inheritance) and object association, and within object association, differentiate simple association (weak, no ownership), composition (strong, part-of, filled diamond), and aggregation (weaker, has-a, unfilled diamond). Understanding the UML notations for these relationships is crucial for conceptual modeling.
π§ Quick Revision Questions
- What is the diamond problem in multiple inheritance, and what causes it?
- Explain the difference between a one-way and a two-way association, and provide a real-world example for each.
- Describe the key difference between composition and aggregation in terms of object lifecycle and dependency.
- If a Mermaid class inherits from both
WomanandFish, and both base classes have aswim()method, what is the ambiguity problem, and how can it be resolved? - A
LibraryhasBooks. Can aBookexist independently of theLibrary? Which type of association (simple, composition, or aggregation) best describes this relationship?
π Lecture 6 β Class Compatibility, Polymorphism & Object-Oriented Modeling
π Overview: This lecture introduces two fundamental OOP concepts: class compatibility (subtyping) and polymorphism. It then applies these concepts through a complete, step-by-step example of modeling a graphic editor, demonstrating how to identify classes, associations, attributes, operations, and inheritance from a problem statement.
ποΈ Topics Covered
The lecture covers class compatibility and the definition of a subtype (behavioral compatibility), the general concept of polymorphism and its specific meaning in the OO model with examples and advantages, followed by a comprehensive object-oriented modeling example that demonstrates identifying classes, eliminating irrelevant ones, finding associations, identifying attributes and operations, and identifying inheritance.
π Lecture Summary
Class Compatibility
A class is behaviorally compatible with another if it supports all the operations of the other class. Such a class is called a subtype. A class can be replaced by its subtype. A derived class is usually a subtype of the base class because it can handle all the legal messages (operations) of the base class. Therefore, a base class can always be replaced by the derived class. For example, a Shape class with attributes (color, vertices) and operations (move, setColor, draw) has derived classes Circle, Line, and Triangle. All three derived classes are behaviorally compatible with the base class. Similarly, a File class can be replaced by any of its child classes (ASCII File, PDF File, PS File).
Polymorphism
In general, polymorphism refers to the existence of different forms of a single entity. For example, both Diamond and Coal are different forms of Carbon.
Polymorphism in OO Model
In the OO model, polymorphism means that different objects can behave in different ways for the same message (stimulus). Consequently, the sender of a message does not need to know the exact class of the receiver. The sender sends a message to the receiver, and the appropriate method is called on the receiver side.
- Example 1 β Shape Hierarchy: An Editor sends a
drawmessage to a Shape class. Thedrawmethod is called according to the nature of the actual object present (e.g.,Line.draw(),Circle.draw(),Triangle.draw()). - Example 2 β File Hierarchy: An Editor sends a
printmessage to a File class. Theprintmethod is called based on the actual child object of the File class (e.g.,ASCII_File.print(),PDF_File.print(),PS_File.print()). The message is the same, but the appropriate execution will be done based on the receiver.
π‘ Why this matters: Polymorphism allows the same message to trigger different behaviors, making systems flexible and extensible.
Polymorphism β Advantages
- Messages can be interpreted in different ways depending upon the receiver class.
- New classes can be added without changing the existing model. For example, if a new Square class is added to the Shape hierarchy, it only needs to implement its own
draw()method. The Editor can still send the samedrawmessage without any code changes. - In general, polymorphism is a powerful tool to develop flexible and reusable systems.
Object-Oriented Modeling an Example
Problem Statement: Develop a graphic editor that can draw different geometric shapes such as line, circle and triangle. User can select, move or rotate a shape. To do so, editor provides user with a menu listing different commands. Individual shapes can be grouped together and can behave as a single shape.
1. Identify Classes: Extract nouns from the problem statement: Editor, Line, Circle, Triangle, Shape, User, Menu, Commands, Group.
- Eliminate irrelevant classes:
- Editor β Very broad scope. It is the name of the overall system, so we will not make its object. It is marked as irrelevant.
- User β Out of system boundary; it is interacting with the system from outside.
- Add classes by analyzing requirements:
- Group (of shapes) β Required to behave as a shape, so it should behave as an object.
- View β A graphic editor must have a display area to show shapes. We add this using domain knowledge.
- Final Classes: Shape, Line, Circle, Triangle, Menu, Group, View.
2. Finding Associations: Find relationships between objects.
- Identify Associations: Extract verbs connecting objects.
- "Individual shapes can be grouped together" β Group consists of Line, Circle, Triangle (and other groups). This is a Composition relationship.
- Verify access paths:
- View contains (draws) shapes (Line, Circle, Triangle, Group). This is an Aggregation relationship.
- Menu sends message to View. This is a Simple One-Way Association.
3. Identify Attributes: Extract properties from domain knowledge.
- Line: Color, Vertices, Length
- Circle: Color, Vertices, Radius
- Triangle: Color, Vertices, Angle
- Shape: Color, Vertices
- Group: noOfObjects
- View: noOfObjects, selected
- Menu: Name, isOpen
4. Identify Operations: Extract verbs connected with an object from the problem statement: "draw", "select", "move", "rotate", "group", "open", "provide".
- Eliminate irrelevant operations: "Develop" is out of system boundary. "Behave" has broad semantics.
- Selected operations per class:
- Line, Circle, Triangle, Shape, Group: draw(), select(), move(), rotate()
- Menu: open(), select(), move(), rotate()
- Extract operations using domain knowledge:
- View: add(), remove(), group(), show(), select(), move(), rotate()
5. Identify Inheritance: Search for "is a kind of" relationships.
- From "shapes such as line, circle and triangle" β Line, Circle, Triangle inherit from Shape.
- From "Individual shapes can be grouped together and can behave as a single shape" β Group inherits from Shape.
Refining the Object Model: Application of inheritance demands an iteration over the whole object model. In the inheritance hierarchy:
- All attributes are shared:
Color,verticesare moved to Shape. - All associations are shared: View contains all kinds of shapes. Group consists of all kinds of shapes.
- Some operations are shared:
select(),move(),rotate()are shared from Shape. - Other operations are overridden: The implementation of
draw()is specific to Line, Circle, Triangle, and Group (they override the basedraw()).
β Key Takeaways
You must understand that class compatibility means a derived class can replace its base class because it supports all base class operations, making it a subtype. Polymorphism is the ability for different objects to respond to the same message in different ways, enabling flexible and reusable systems. The graphic editor example demonstrates the complete OO modeling process: extracting nouns for classes, eliminating irrelevant ones, identifying associations (aggregation, composition, simple association) from verbs, and finding inheritance from "is-a" relationships. Finally, when inheritance is applied, you must refine the object model by sharing attributes, associations, and common operations up the hierarchy, while allowing specific implementations (like draw()) to be overridden in derived classes.
π§ Quick Revision Questions
- What does it mean for a class to be behaviorally compatible with another class?
- In the context of OOP, what does polymorphism mean?
- What are the two main advantages of polymorphism mentioned in the lecture?
- In the graphic editor modeling example, why was the Editor class considered irrelevant?
- What is the difference between a shared operation and an overridden operation in an inheritance hierarchy?