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 and abstract 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 with CPU, RAM, and HardDrive.
  • Demonstrate aggregation with Employee and Address.
  • Create an association between Doctor and Patient.
  • Write a class Order that depends on PaymentProcessor.

๐Ÿ™ Acknowledgments

Sources:

  • StackOverflow
  • GeeksforGeeks
  • C# Corner
  • Medium
  • ChatGPT Assistance (2025 sessions)