.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)
  • Object: customer1 = new Customer("Ramesh", "9800123456", 0)
    • When a user tops up via the Ncell app, the TopUp() method updates Balance.

2. Inheritance

Definition:

  • Inheritance allows a derived class (child) to inherit properties/methods from a base class (parent).
  • Uses : BaseClass syntax.
  • 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()
  • Derived Class: FoodOrder : Order
    • Additional Property: string RestaurantName
    • Overridden Method: void ProcessPayment() { /* Fast-track payment */ }

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()
  • Derived Classes:
    • BikeRide : Ride → Overrides CalculateFare() with bike-specific logic.
    • CarRide : Ride → Overrides CalculateFare() 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:

accountDeposit(1000)_balance = 1000 (private)TOP
State after Deposit() call (private field _balance updated)

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).

5. Abstraction

Definition:

  • Hiding complex implementation details, exposing only essential features.
  • Achieved via:
    • Abstract classes (abstract keyword),
    • Interfaces (interface keyword).

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).
  • Concrete Classes: RetailTrader : ITrader, InstitutionalTrader : ITrader (each implements ITrader differently).

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).
  • 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

  1. Modularity: Code is organized into objects (easier maintenance).
  2. Reusability: Inheritance reduces redundant code.
  3. Scalability: Large applications (e.g., banks, e-commerce) are easier to design.
  4. Security: Encapsulation protects data (e.g., private fields in BankAccount).

Disadvantages

  1. Complexity: Steeper learning curve than procedural programming.
  2. Performance Overhead: Method calls in OOP may be slower than direct function calls.
  3. Design Time: Requires careful planning (e.g., class hierarchies).

In the Real World

  1. Khalti’s Payment System

    • Uses inheritance to classify transactions:
      • Base class: Transaction
      • Derived classes: CreditTransaction, DebitTransaction, RefundTransaction.
    • Polymorphism is used to process each transaction type differently (e.g., Process() method behaves uniquely for each).
  2. NTC’s Network Management

    • Interfaces define standards for devices:
      • INetworkDevice interface with Connect() and Disconnect() methods.
      • Classes like Router : INetworkDevice and Switch : INetworkDevice implement these methods.
  3. Pathao’s Ride Matching Algorithm

    • Abstraction hides complex logic:
      • IRideMatcher interface defines MatchRider(Driver driver).
      • Concrete classes like UrbanMatcher and SuburbanMatcher implement different matching algorithms.

Exam Tip

  1. Code Tracing: Always show state after each step (e.g., stack/heap changes in inheritance).
  2. 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
  3. Key Shortcuts:
    • Use override for runtime polymorphism.
    • Use abstract for incomplete base classes.
    • Use interface for multiple inheritance-like behavior.
  4. Common Pitfalls:
    • Forgetting virtual/override in polymorphism.
    • Misusing private vs protected access modifiers.
    • Confusing abstraction (hiding details) with encapsulation (bundling data/methods).

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:

InheritanceRuntime BindingAnimalDogPolymorphic Call
Polymorphism in action: Animal reference calling Dog's overridden method

Based on the TU BITM syllabus for .NET Programming (IT275), unit 3.

Discussion

Loading…