CACS408 Dot Net Technology

Dot Net TechnologyUnit 210 min read

OOP in C: Classes, Objects, Inheritance, Polymorphism & Encapsulation

Unit 2 of Dot Net Technology covers the core principles of Object-Oriented Programming (OOP) in C, including classes, objects, inheritance, polymorphism, encapsulation, and abstraction. It explains how these concepts are implemented in C with practical examples, comparisons, and real-world applications.

TAKEAWAYS:

  • Understand the four pillars of OOP (encapsulation, inheritance, polymorphism, and abstraction) and how they are implemented in C#.
  • Learn how to define classes, create objects, and use constructors in C#.
  • Differentiate between object-oriented programming (OOP) and object-based programming (OBP).
  • Explore inheritance, method overriding, and polymorphism with practical examples.
  • Understand delegates, events, and interfaces in C# and their real-world applications.
  • Apply OOP concepts to design real-world systems like banking, e-commerce, or transportation.

1. Introduction to Object-Oriented Programming (OOP) in C#

OOP is a programming paradigm that organizes software design around objects rather than functions and logic. C# is a pure OOP language, meaning everything in it is an object (even primitive types like int are objects in C#).

Key Concepts of OOP

OOP is built on four fundamental principles:

  1. Encapsulation – Bundling data (fields) and methods (functions) into a single unit (class) while restricting direct access.
  2. Inheritance – A mechanism where a new class (child) inherits properties and behaviors from an existing class (parent).
  3. Polymorphism – The ability of an object to take many forms (e.g., method overloading, overriding).
  4. Abstraction – Hiding complex implementation details and exposing only essential features.

OOP vs. Object-Based Programming (OBP)

Feature Object-Oriented Programming (OOP) Object-Based Programming (OBP)
Inheritance Supports inheritance Does not support inheritance
Polymorphism Supports polymorphism Does not support polymorphism
Encapsulation Strong encapsulation Weak encapsulation
Example Languages C++, Java, C# JavaScript, Python (partial)

Why is C# considered "safe"?

  • Type Safety: C# enforces strict type checking (e.g., int cannot be assigned to a string without conversion).
  • Memory Safety: Uses garbage collection to automatically manage memory.
  • Exception Handling: Supports structured error handling (try-catch-finally).
  • Security: Restricts unsafe operations (e.g., pointer arithmetic is not allowed by default).

2. Classes and Objects in C#

A class is a blueprint for creating objects, while an object is an instance of a class.

Defining a Class

public class Student
{
    // Fields (data members)
    public string Name;
    public int RollNumber;

    // Constructor
    public Student(string name, int rollNumber)
    {
        Name = name;
        RollNumber = rollNumber;
    }

    // Method (behavior)
    public void DisplayInfo()
    {
        Console.WriteLine($"Name: {Name}, Roll: {RollNumber}");
    }
}

Creating an Object

Student student1 = new Student("Ramesh", 101);
student1.DisplayInfo(); // Output: Name: Ramesh, Roll: 101

Constructors in C#

  • Default Constructor: Automatically provided if no constructor is defined.
  • Parameterized Constructor: Takes arguments to initialize objects.
  • Constructor Overloading: Multiple constructors with different parameters.
flowchart TD
    A["Class Definition"] --> B["Fields (Name, RollNumber)"]
    A --> C["Constructor (Student(string, int))"]
    A --> D["Method (DisplayInfo())"]
    B --> E["Object Creation: new Student(\"Ramesh\", 101)"]
    C --> E
    D --> F["student1.DisplayInfo()"]

3. Encapsulation in C#

Encapsulation restricts direct access to data and ensures controlled modification via getters and setters.

Example: Bank Account

public class BankAccount
{
    private decimal _balance; // Private field

    public string AccountHolder { get; set; } // Public property

    public decimal Balance
    {
        get { return _balance; } // Getter
        private set // Private setter (only accessible within class)
        {
            if (value >= 0)
                _balance = value;
            else
                Console.WriteLine("Invalid balance!");
        }
    }

    public void Deposit(decimal amount)
    {
        if (amount > 0)
            _balance += amount;
    }
}

Real-World Example: Ncell Wallet (Khalti)

  • Encapsulation: Khalti stores user balance privately and provides controlled methods (Deposit(), Withdraw()) to modify it.
  • Security: Prevents unauthorized access to sensitive data.

4. Inheritance in C#

Inheritance allows a derived class (child) to inherit properties and methods from a base class (parent).

Syntax

public class Animal // Base class
{
    public void Eat()
    {
        Console.WriteLine("Eating...");
    }
}

public class Dog : Animal // Derived class
{
    public void Bark()
    {
        Console.WriteLine("Barking...");
    }
}

Types of Inheritance

  1. Single Inheritance (C# supports only this)
  2. Multilevel Inheritance
  3. Hierarchical Inheritance
  4. Multiple Inheritance (Not directly supported; use interfaces instead)

Real-World Example: Daraz Order Processing

  • Base Class: Order
    • Fields: OrderId, Customer, TotalAmount
    • Methods: PlaceOrder(), CancelOrder()
  • Derived Class: FoodOrder (inherits from Order)
    • Additional Method: AddDeliveryCharge()

5. Polymorphism in C#

Polymorphism allows one interface to be used for different data types.

Types of Polymorphism

  1. Compile-Time Polymorphism (Method Overloading)

    • Same method name, different parameters.
    public class Calculator
    {
        public int Add(int a, int b) => a + b;
        public double Add(double a, double b) => a + b;
    }
    
  2. Run-Time Polymorphism (Method Overriding)

    • Child class provides a new implementation of a base class method.
    public class Shape
    {
        public virtual void Draw() => Console.WriteLine("Drawing a shape");
    }
    
    public class Circle : Shape
    {
        public override void Draw() => Console.WriteLine("Drawing a circle");
    }
    

Real-World Example: NTC Traffic Management

  • Base Class: Vehicle
    • Method: CalculateToll()
  • Derived Classes:
    • Car (overrides CalculateToll() to return Rs. 50)
    • Bus (overrides CalculateToll() to return Rs. 200)

6. Abstraction in C#

Abstraction hides complex logic and exposes only essential features using abstract classes and interfaces.

Abstract Class

public abstract class Vehicle
{
    public abstract void Start(); // Abstract method (no body)
    public void Display() => Console.WriteLine("Vehicle details");
}

public class Car : Vehicle
{
    public override void Start() => Console.WriteLine("Car started with key");
}

Interface

public interface ILogger
{
    void Log(string message); // No implementation
}

public class FileLogger : ILogger
{
    public void Log(string message) => Console.WriteLine($"Logged to file: {message}");
}

Real-World Example: WhatsApp Messaging

  • Interface: IMessageService
    • Methods: SendMessage(), ReceiveMessage()
  • Implementations:
    • WhatsAppService (implements IMessageService)
    • EmailService (also implements IMessageService)

7. Delegates and Events in C#

Delegates are type-safe function pointers, while events enable event-driven programming.

Delegate Example

public delegate void NotifyDelegate(string message);

public class NotificationService
{
    public event NotifyDelegate OnNotification;

    public void SendNotification(string message)
    {
        OnNotification?.Invoke(message); // Invokes all subscribed methods
    }
}

Real-World Example: Pathao Ride Alerts

  • Delegate: RideStatusDelegate
    • Methods: OnRideStarted(), OnRideCompleted()
  • Usage: When a ride starts, OnRideStarted() is triggered to update the driver and passenger.

8. Exam Tip

  • Differentiate OOP and OBP: Always mention inheritance and polymorphism as key differences.
  • Constructors: Remember default, parameterized, and constructor overloading.
  • Encapsulation: Use private fields with public getters/setters where needed.
  • Inheritance: C# supports only single inheritance; use interfaces for multiple inheritance.
  • Polymorphism: Distinguish between compile-time (overloading) and run-time (overriding).
  • Abstraction: Know when to use abstract classes vs. interfaces.
  • Delegates/Events: Understand event subscription and invocation.

## In the real world

  1. Khalti (Digital Wallet)

    • Encapsulation: User balance is private; Deposit() and Withdraw() methods control access.
    • Polymorphism: Different payment methods (UPI, Credit Card) implement the same IPayment interface.
  2. Daraz (E-Commerce)

    • Inheritance: Order (base) → FoodOrder, ElectronicsOrder (derived).
    • Abstraction: ShippingService interface defines CalculateCost(), implemented by RoadShipping and AirShipping.
  3. Ncell (Telecom Billing)

    • Delegates: BillNotificationDelegate triggers alerts when a bill is generated.
    • Polymorphism: Different Customer types (Prepaid, Postpaid) override CalculateBill().

## Worked Example: Bank Loan Interest Calculation Problem: Calculate monthly interest for a loan using encapsulation and polymorphism.

public abstract class Loan
{
    public decimal Principal { get; set; }
    public decimal Rate { get; set; }

    public abstract decimal CalculateMonthlyInterest();
}

public class HomeLoan : Loan
{
    public override decimal CalculateMonthlyInterest()
    {
        return (Principal * Rate) / 12;
    }
}

public class CarLoan : Loan
{
    public override decimal CalculateMonthlyInterest()
    {
        return (Principal * Rate * 1.1m) / 12; // 10% higher rate
    }
}

Trace Table:

Step Action Principal Rate Monthly Interest
1 HomeLoan loan1 = new HomeLoan() 1,000,000 8% -
2 loan1.Principal = 1000000 1,000,000 8% -
3 loan1.Rate = 0.08m 1,000,000 8% -
4 loan1.CalculateMonthlyInterest() 1,000,000 8% 6,666.67

Real-World Tie-In:

  • Nepal Bank Limited uses similar OOP principles to calculate different loan types (Home, Business, Personal) with varying interest rates.

## Visuals

classDiagram
    class Animal {
        +Eat()
    }
    class Dog {
        +Bark()
    }
    Animal <|-- Dog : Inherits
empty
When a Circle object is referenced as Shape and Draw() is called, the Circle's overridden method executes.

Based on the TU BCA syllabus for Dot Net Technology (CACS408), unit 2.

Discussion

Loading…