Session 5: Interfaces and Object-Oriented Relationships
๐ Overview
In this session, we explored:
- The concept and syntax of Interfaces in C#
- Implementation of interfaces in real scenarios
- Comparison of Abstract Classes vs Interfaces
- Key OOP relationships: Inheritance, Composition, Aggregation, Association, and Dependency
- Applying these relationships in a Library Management System
๐ Topics Covered
Interfaces in C#
Interfaces define contracts that classes must fulfill. They enable loose coupling and multiple inheritance in C#.
- Syntax:
interface IMyInterface { void Method(); }
- Implementation:
class MyClass : IMyInterface
- All members are
public
andabstract
by default - Cannot contain fields
- Supports multiple inheritance
Interface Example
interface IDisplayer { void Display(); }
class Test : IDisplayer {
public void Display() => Console.WriteLine("Hello from interface!");
}
### Abstract Class vs Interface
|Feature|Abstract Class|Interface|
|---|---|---|
|Implementation Allowed?|Yes|No|
|Multiple Inheritance|No|Yes|
|Constructors|Yes|No|
|Fields|Yes|No|
|Use Case|Partial abstraction|Full abstraction|
### OOP Relationships
#### Inheritance (IS-A)
- A class inherits members from another class.
- Promotes reusability.
```c#
class Person { }
class Student : Person { }
Composition (PART-OF)
- Objects are composed of other objects.
- Strong lifecycle dependency.
class Engine { }
class Car { Engine engine = new Engine(); }
Association (HAS-A)
- Loose relationship between objects.
- Both can exist independently.
class Teacher { }
class School {
public void AddTeacher(Teacher t) { }
}
Aggregation (WEAK-PART-OF)
- Special association where one object โownsโ another but the owned object can exist independently.
class Address { }
class Student {
public Address address;
}
Dependency
- Temporary usage of one class by another.
class Printer { void Print(string msg) => Console.WriteLine(msg); }
class Report { void Generate(Printer p) => p.Print("Report"); }
Applied Example: Library Management System
A real-world example combining all relationships:
- Person โ Member/Librarian (Inheritance)
- Library โ Bookshelf โ Book (Composition)
- Member โ LibraryCard (Association)
- Member โ Address (Aggregation)
- Report.Generate(Printer) (Dependency)
โ See full code snippet here or review it during the live session.
๐งช Practice Tasks
- Implement an
IVehicle
interface in two different classes. - Use composition to build a
Computer
withCPU
,RAM
, andHardDrive
. - Demonstrate aggregation with
Employee
andAddress
. - Create an association between
Doctor
andPatient
. - Write a class
Order
that depends onPaymentProcessor
.
๐ Acknowledgments
Sources:
- StackOverflow
- GeeksforGeeks
- C# Corner
- Medium
- ChatGPT Assistance (2025 sessions)