.NET ProgrammingUnit 310 min read
OOP in C: Classes, Inheritance, Polymorphism & Abstraction
Unit 3 of .NET Programming covers classes and objects, inheritance, polymorphism, encapsulation, abstraction, and interfaces in C with real-world examples, code traces, and exam-focused comparisons.
Core Concepts of Object-Oriented Programming (OOP)
1. Classes and Objects
Definition:
- A class is a blueprint for creating objects (e.g.,
Car,BankAccount). - An object is an instance of a class (e.g.,
myCar = new Car()). - Properties define attributes (e.g.,
string Model). - Methods define behaviors (e.g.,
void StartEngine()).
How It Works in C#
public class Car
{
// Properties (data members)
public string Model { get; set; }
public int Year { get; set; }
// Constructor
public Car(string model, int year)
{
Model = model;
Year = year;
}
// Method (behavior)
public void DisplayInfo()
{
Console.WriteLine($"Model: {Model}, Year: {Year}");
}
}
Trace Example:
flowchart TD
A["Car myCar = new Car(\"Toyota\", 2020)"] --> B["myCar.Model = \"Toyota\""]
B --> C["myCar.Year = 2020"]
C --> D["myCar.DisplayInfo() --> \"Model: Toyota, Year: 2020\""]Real-World Example: Ncell’s Customer Management
Ncell uses classes to model customers, subscriptions, and billing:
- Class:
Customer- Properties:
string Name,string PhoneNumber,decimal Balance - Method:
void TopUp(decimal amount)
- Properties:
- Object:
customer1 = new Customer("Ramesh", "9800123456", 0)- When a user tops up via the Ncell app, the
TopUp()method updatesBalance.
- When a user tops up via the Ncell app, the
2. Inheritance
Definition:
- Inheritance allows a derived class (child) to inherit properties/methods from a base class (parent).
- Uses
: BaseClasssyntax. - Types: Single, multilevel, hierarchical, multiple (via interfaces).
Example: Vehicle Hierarchy
public class Vehicle
{
public string Brand { get; set; }
public void DisplayBrand() => Console.WriteLine($"Brand: {Brand}");
}
public class Car : Vehicle // Inherits from Vehicle
{
public string Model { get; set; }
public void DisplayModel() => Console.WriteLine($"Model: {Model}");
}
Trace:
classDiagram
class Vehicle {
+string Brand
+void DisplayBrand()
}
class Car {
+string Model
+void DisplayModel()
}
Vehicle <|-- Car : Inherits
note for Car "myCar = new Car()\nmyCar.Brand = 'Toyota' (inherited)\nmyCar.Model = 'Corolla' (own property)"Real-World Example: Daraz’s Order Processing
Daraz uses inheritance to classify orders:
- Base Class:
Order- Properties:
string OrderId,decimal TotalAmount - Method:
void ProcessPayment()
- Properties:
- Derived Class:
FoodOrder : Order- Additional Property:
string RestaurantName - Overridden Method:
void ProcessPayment() { /* Fast-track payment */ }
- Additional Property:
3. Polymorphism
Definition:
- "Many forms" – same method name, different implementations.
- Compile-time (Method Overloading): Same name, different parameters.
- Run-time (Method Overriding): Base class method redefined in derived class.
Example: Shape Area Calculation
public class Shape
{
public virtual double Area() => 0; // Virtual method
}
public class Circle : Shape
{
public double Radius { get; set; }
public override double Area() => Math.PI * Radius * Radius; // Override
}
Trace Table:
| Step | Action | Output (Area) |
|---|---|---|
Shape shape = new Circle() |
Polymorphic call: shape.Area() |
3.1416 * R² |
Real-World Example: Pathao’s Fare Calculation
Pathao uses polymorphism to calculate fares for different ride types:
- Base Class:
Ride- Method:
decimal CalculateFare()
- Method:
- Derived Classes:
BikeRide : Ride→ OverridesCalculateFare()with bike-specific logic.CarRide : Ride→ OverridesCalculateFare()with car logic.
4. Encapsulation
Definition:
- Bundling data (properties) and methods into a single unit (class).
- Access modifiers:
public(accessible everywhere),private(only within the class),protected(within class + derived classes),internal(within the same assembly).
Example: Bank Account
public class BankAccount
{
private decimal _balance; // Private field
public void Deposit(decimal amount)
{
if (amount > 0) _balance += amount;
}
public decimal GetBalance() => _balance; // Public getter
}
Trace:
Real-World Example: eSewa’s Transaction Security
eSewa uses encapsulation to hide sensitive data:
- Class:
Transaction- Private Field:
string _password(never exposed). - Public Method:
bool VerifyPassword(string input)(validates without exposing_password).
- Private Field:
5. Abstraction
Definition:
- Hiding complex implementation details, exposing only essential features.
- Achieved via:
- Abstract classes (
abstractkeyword), - Interfaces (
interfacekeyword).
- Abstract classes (
Example: Abstract Class
public abstract class Animal
{
public abstract void MakeSound(); // No implementation
}
public class Dog : Animal
{
public override void MakeSound() => Console.WriteLine("Bark!");
}
Trace:
classDiagram
abstract class Animal {
+abstract void MakeSound()
}
class Dog {
+void MakeSound()
}
Animal <|-- Dog : Implements
note for Dog "myDog.MakeSound()\nOutput: 'Bark!'"
note for Animal "Abstract base class"
note for Dog "Concrete implementation"Real-World Example: NEPSE’s Stock Trading
NEPSE uses abstraction to define trading rules:
- Interface:
ITrader- Methods:
void Buy(string symbol, int quantity),void Sell(string symbol, int quantity).
- Methods:
- Concrete Classes:
RetailTrader : ITrader,InstitutionalTrader : ITrader(each implementsITraderdifferently).
6. Interfaces
Definition:
- A contract defining methods a class must implement.
- Syntax:
interface IName { void Method(); } - Key Points:
- No implementation (only method signatures).
- A class can implement multiple interfaces.
Example: IDisposable Interface
public interface IDisposable
{
void Dispose(); // Must be implemented
}
public class FileHandler : IDisposable
{
public void Dispose() => Console.WriteLine("File closed.");
}
Trace:
classDiagram
interface IDisposable {
+void Dispose()
}
class FileHandler {
+void Dispose()
}
IDisposable <|-- FileHandler : Implements
note for FileHandler "file.Dispose()\nOutput: 'File closed.'"
note for IDisposable "Interface contract"Real-World Example: WhatsApp’s Message Protocol
WhatsApp uses interfaces to standardize message handling:
- Interface:
IMessageHandler- Methods:
void Send(string message),void Receive(string message).
- Methods:
- Classes:
WhatsAppClient : IMessageHandler(implements for WhatsApp).EmailClient : IMessageHandler(implements for email).
Comparison Tables
| Feature | Class | Interface |
|---|---|---|
| Definition | Blueprint for objects | Contract for methods |
| Implementation | Can have methods + data | Only method signatures |
| Inheritance | Single (extends one class) | Multiple (implements many) |
| Access Modifiers | Supports all (public, private) |
All methods are public by default |
| Polymorphism Type | Example | Use Case |
|---|---|---|
| Compile-time | void Add(int a) vs void Add(double a) |
Method overloading (e.g., Console.WriteLine) |
| Run-time | baseClass obj = new DerivedClass() |
Dynamic method calls (e.g., Shape.Area()) |
Advantages and Disadvantages of OOP
Advantages
- Modularity: Code is organized into objects (easier maintenance).
- Reusability: Inheritance reduces redundant code.
- Scalability: Large applications (e.g., banks, e-commerce) are easier to design.
- Security: Encapsulation protects data (e.g.,
privatefields inBankAccount).
Disadvantages
- Complexity: Steeper learning curve than procedural programming.
- Performance Overhead: Method calls in OOP may be slower than direct function calls.
- Design Time: Requires careful planning (e.g., class hierarchies).
In the Real World
Khalti’s Payment System
- Uses inheritance to classify transactions:
- Base class:
Transaction - Derived classes:
CreditTransaction,DebitTransaction,RefundTransaction.
- Base class:
- Polymorphism is used to process each transaction type differently (e.g.,
Process()method behaves uniquely for each).
- Uses inheritance to classify transactions:
NTC’s Network Management
- Interfaces define standards for devices:
INetworkDeviceinterface withConnect()andDisconnect()methods.- Classes like
Router : INetworkDeviceandSwitch : INetworkDeviceimplement these methods.
- Interfaces define standards for devices:
Pathao’s Ride Matching Algorithm
- Abstraction hides complex logic:
IRideMatcherinterface definesMatchRider(Driver driver).- Concrete classes like
UrbanMatcherandSuburbanMatcherimplement different matching algorithms.
- Abstraction hides complex logic:
Exam Tip
- Code Tracing: Always show state after each step (e.g., stack/heap changes in inheritance).
- Diagrams: Draw UML class diagrams for inheritance/polymorphism questions.
- Example:
classDiagram class Vehicle { +string Brand +void DisplayBrand() } class Car { +string Model +void DisplayModel() } Vehicle <|-- Car : Inherits
- Example:
- Key Shortcuts:
- Use
overridefor runtime polymorphism. - Use
abstractfor incomplete base classes. - Use
interfacefor multiple inheritance-like behavior.
- Use
- Common Pitfalls:
- Forgetting
virtual/overridein polymorphism. - Misusing
privatevsprotectedaccess modifiers. - Confusing abstraction (hiding details) with encapsulation (bundling data/methods).
- Forgetting
Practice Question: Given the following classes, trace the output of:
public class Animal { public virtual void Sound() => Console.WriteLine("Generic"); }
public class Dog : Animal { public override void Sound() => Console.WriteLine("Bark"); }
class Program { static void Main() { Animal a = new Dog(); a.Sound(); } }
Answer:
Based on the TU BITM syllabus for .NET Programming (IT275), unit 3.
Discussion
Loading…