Monday, 17 November 2025

Method Hiding in C#

Method Hiding in C#

Method Hiding

Method hiding occurs when a derived class defines a method with the same name as a method in the base class but uses the new keyword. The version of the method called depends on the reference type.

C# Example:

using System; class Car { public void Start() { Console.WriteLine("Car is starting."); } } class SportsCar : Car { public new void Start() { Console.WriteLine("SportsCar is starting with turbo!"); } } class Program { static void Main() { Car carRef = new Car(); carRef.Start(); SportsCar sportsCarRef = new SportsCar(); sportsCarRef.Start(); Car baseRef = new SportsCar(); baseRef.Start(); } }

Output:

Car is starting. SportsCar is starting with turbo! Car is starting.

Function Overriding Example in C#

Function Overriding Example in C#

Function Overriding Example

In this example, the Start method is overridden in the derived class SportsCar using the override keyword. This demonstrates runtime polymorphism.

C# Example:

using System; class Car { public virtual void Start() { Console.WriteLine("Car is starting."); } } class SportsCar : Car { public override void Start() { Console.WriteLine("SportsCar is starting with turbo!"); } } class Program { static void Main() { Car myCar = new Car(); myCar.Start(); SportsCar mySportsCar = new SportsCar(); mySportsCar.Start(); Car carRef = new SportsCar(); carRef.Start(); } }

Output:

Car is starting. SportsCar is starting with turbo! SportsCar is starting with turbo!

Static Binding in C#

Static Binding in C#

Static Binding

Static binding, also called early binding, means that the method to be executed is determined at compile time. It is used in compile-time polymorphism such as method overloading and operator overloading.

Key Points:

  • Resolved at compile time.
  • Occurs in method overloading or operator overloading.
  • Faster than dynamic binding.
  • Opposite of dynamic (late) binding.

C# Example:

class Calculator { public int Add(int a, int b) { return a + b; } public double Add(double a, double b) { return a + b; } } class Program { static void Main() { Calculator calc = new Calculator(); Console.WriteLine(calc.Add(2, 3)); Console.WriteLine(calc.Add(2.5, 3.5)); } }

Output:

5 6

Dynamic Binding in C#

Dynamic Binding in C#

Dynamic Binding

Dynamic binding, also known as late binding, means that the method to execute is determined at runtime based on the actual object being referred to. It is used in runtime polymorphism.

Key Points:

  • Resolved at runtime.
  • Occurs during method overriding.
  • Requires virtual and override.
  • Base class reference can call derived class methods.

C# Example:

class Car { public virtual void Drive() { Console.WriteLine("Car is driving."); } } class SportsCar : Car { public override void Drive() { Console.WriteLine("SportsCar is driving fast!"); } } class Program { static void Main() { Car c = new SportsCar(); c.Drive(); } }

Output:

SportsCar is driving fast!

Function Overriding in C#

Function Overriding in C#

Function Overriding

Function overriding means defining the same method in a derived class that already exists in the base class, using the same name, parameters, and return type. It is used to change the inherited behavior.

Key Points

  • Requires virtual in the base class.
  • Requires override in the derived class.
  • Method name, parameters, and return type must match exactly.
  • Used for runtime polymorphism.

C# Example:

class Car { public virtual void Drive() { Console.WriteLine("Car is driving."); } } class SportsCar : Car { public override void Drive() { Console.WriteLine("SportsCar is driving very fast!"); } } class Program { static void Main() { Car c = new SportsCar(); c.Drive(); } }

Output:

SportsCar is driving very fast!

Operator Overloading in C#

Operator Overloading in C#

Operator Overloading in C#

Operator overloading allows developers to redefine the behavior of operators (like +, -, *, ==) for custom classes and structs. It makes objects behave like built-in types when using operators.

Key Points:

  • Uses the operator keyword.
  • Must be defined inside a class or struct.
  • At least one parameter must be a user-defined type.

C# Example:

class CarSpeed { public int Speed { get; set; } public CarSpeed(int speed) { Speed = speed; } public static CarSpeed operator +(CarSpeed c1, CarSpeed c2) { return new CarSpeed(c1.Speed + c2.Speed); } } class Program { static void Main() { CarSpeed car1 = new CarSpeed(60); CarSpeed car2 = new CarSpeed(40); CarSpeed total = car1 + car2; Console.WriteLine("Total Speed: " + total.Speed); } }

Output:

Total Speed: 100

Overloading Main Method

Overloading Main Method

Can You Overload the Main Method in C#?

Yes, you can overload the Main method in C#, but only one serves as the program's entry point.

Example:

class Program { static void Main(string[] args) { Console.WriteLine("Main with string[] args"); Main(10); } static void Main(int number) { Console.WriteLine("Overloaded Main with int: " + number); } static void Main(double value) { Console.WriteLine("Overloaded Main with double: " + value); } }

Key Points:

  • You can overload Main like any other method.
  • Only one method is used as the entry point.
  • Overloaded Main methods must be called manually.

Compile-time Polymorphism

Compile-time Polymorphism

Compile-time Polymorphism in C#

Compile-time polymorphism, also called static polymorphism, means that the method to be executed is decided during compile time. It is mainly achieved through method overloading in C#.

Features:

  • Decided at compile time
  • Achieved using method overloading
  • Occurs within the same class
  • Faster than runtime polymorphism

C# Example:

class Calculator { public int Add(int a, int b) { return a + b; } public double Add(double a, double b) { return a + b; } public int Add(int a, int b, int c) { return a + b + c; } } class Program { static void Main() { Calculator c = new Calculator(); Console.WriteLine(c.Add(2, 3)); Console.WriteLine(c.Add(2.5, 3.1)); Console.WriteLine(c.Add(1, 2, 3)); } }

Runtime Polymorphism

Runtime Polymorphism

Runtime Polymorphism in C#

Runtime polymorphism (dynamic polymorphism) means that the method to be executed is decided during runtime. It is achieved through method overriding using the virtual and override keywords.

Features:

  • Achieved using method overriding
  • Uses virtual and override
  • Method selection happens at runtime
  • Enables dynamic and flexible behavior

C# Example:

class Car { public virtual void Drive() { Console.WriteLine("Car is driving."); } } class SportsCar : Car { public override void Drive() { Console.WriteLine("SportsCar is driving fast!"); } } class Program { static void Main() { Car c = new SportsCar(); c.Drive(); } }

Output:

SportsCar is driving fast!

Overloading vs Overriding

Overloading vs Overriding

Difference Between Overloading and Overriding in C#

1. Method Overloading

  • Same method name, different parameters.
  • Occurs within the same class.
  • Compile-time (static) polymorphism.
  • Parameters must change (type, number, or order).

C# Example:

class Calculator { public int Add(int a, int b) { return a + b; } public double Add(double a, double b) { return a + b; } public int Add(int a, int b, int c) { return a + b + c; } }

2. Method Overriding

  • Same method name, same parameters.
  • Occurs in different classes using inheritance.
  • Runtime (dynamic) polymorphism.
  • Uses virtual and override keywords.

C# Example:

class Car { public virtual void Drive() { Console.WriteLine("Car is driving"); } } class SportsCar : Car { public override void Drive() { Console.WriteLine("SportsCar is driving fast!"); } }

C# Inheritance Concepts

C# Inheritance Concepts

C# Inheritance & Keywords

1. The sealed Keyword (C# version of Java's final)

C# does not use the keyword final. Instead, it uses sealed to:

  • Stop a class from being inherited
  • Stop a method from being overridden again

Sealed Class Example

sealed class Car { }

Sealed Method Example

class A { public virtual void Show() { } } class B : A { public sealed override void Show() { } }

2. Multilevel Inheritance Example Using Car Classes

Multilevel inheritance means:

Car → SportsCar → RaceCar

C# Example

class Car // Level 1 (Base Class) { public void Start() { Console.WriteLine("Car starts."); } } class SportsCar : Car // Level 2 (Inherits from Car) { public void Turbo() { Console.WriteLine("SportsCar activates turbo."); } } class RaceCar : SportsCar // Level 3 (Inherits from SportsCar) { public void Nitro() { Console.WriteLine("RaceCar boosts with nitro!"); } } class Program { static void Main() { RaceCar rc = new RaceCar(); rc.Start(); // from Car rc.Turbo(); // from SportsCar rc.Nitro(); // from RaceCar } }

Output:

Car starts. SportsCar activates turbo. RaceCar boosts with nitro!

Saturday, 15 November 2025

Multiple Inheritance in C#

Multiple Inheritance in C#

Can a Class Inherit from Multiple Classes in C#?

No. In C#, a class cannot inherit from more than one class directly. This restriction is in place to avoid ambiguity problems such as the diamond problem that can occur in multiple inheritance.

Example (Not Allowed)

class A { }
class B { }

class C : A, B { }  // ❌ This is NOT allowed in C#
    

How C# Handles Multiple Inheritance

  • C# supports multiple inheritance via interfaces. A class can implement multiple interfaces.
  • This avoids ambiguity because interfaces only define method signatures, and the implementing class provides the actual implementation.

Example Using Interfaces

interface IA {
    void MethodA();
}

interface IB {
    void MethodB();
}

class C : IA, IB {
    public void MethodA() {
        Console.WriteLine("MethodA implementation");
    }

    public void MethodB() {
        Console.WriteLine("MethodB implementation");
    }
}
    

Summary: C# does not allow multiple class inheritance, but multiple interfaces can be implemented to achieve similar behavior.

The 'base' Keyword in C#

The 'base' Keyword in C#

The base Keyword in C#

In C#, the base keyword is used to refer to the immediate parent class of the current class. It is similar to the super keyword in Java.

Main Uses of base

  1. Access parent class methods: Call a method in the base class that is overridden in the derived class.
  2. Access parent class constructors: Invoke a constructor of the base class from the derived class constructor.
  3. Access parent class properties or fields: Access members of the base class that are hidden in the derived class.

Examples

1. Calling Base Class Method

class Parent {
    public void Show() {
        Console.WriteLine("Parent Show");
    }
}

class Child : Parent {
    public new void Show() {
        Console.WriteLine("Child Show");
    }

    public void Display() {
        base.Show(); // calls Parent's Show()
    }
}
    

2. Calling Base Class Constructor

class Parent {
    public Parent() {
        Console.WriteLine("Parent Constructor");
    }
}

class Child : Parent {
    public Child() : base() {  // calls Parent constructor
        Console.WriteLine("Child Constructor");
    }
}
    

Note: Use base when you want to explicitly access members or constructors of the parent class from a derived class.

Diamond Problem in Inheritance

Diamond Problem in Inheritance

The Diamond Problem

The diamond problem occurs in multiple inheritance when a class inherits from two classes that both inherit from a common base class. This creates ambiguity about which base class method or property should be used.

Illustration of the Diamond Problem

        A
       / \
      B   C
       \ /
        D
    

Here:

  • Class A is the base class.
  • Classes B and C inherit from A.
  • Class D inherits from both B and C.

Problem: If A has a method Show() and both B and C override it, which version should D inherit? This ambiguity is called the diamond problem.

How C# Handles It

  • C# does not allow multiple class inheritance, so the diamond problem is avoided for classes.
  • Using interfaces, C# allows multiple inheritance without ambiguity because interface methods must be explicitly implemented.

Example with Interfaces in C#

interface IA {
    void Show();
}

interface IB : IA { }
interface IC : IA { }

class D : IB, IC {
    public void Show() {
        Console.WriteLine("Implemented Show in D");
    }
}
    

Here, D explicitly implements the method, resolving any ambiguity.

Types of Inheritance in C#?

Types of Inheritance in C#

Inheritance is a mechanism where one class (derived class) acquires the properties and behaviors of another class (base class). C# supports several types of inheritance:

1. Single Inheritance

A derived class inherits from only one base class.

class Base {
    public void Show() { }
}

class Derived : Base {
    // inherits Show() from Base
}
    

2. Multilevel Inheritance

A class is derived from another derived class, forming a chain.

class GrandParent { }
class Parent : GrandParent { }
class Child : Parent { }
    

3. Hierarchical Inheritance

Multiple classes inherit from a single base class.

class Base { }
class Child1 : Base { }
class Child2 : Base { }
    

4. Multiple Inheritance (via Interfaces)

C# does not support multiple class inheritance directly, but multiple interfaces can be implemented.

interface IA { }
interface IB { }

class Derived : IA, IB { }
    

5. Hybrid Inheritance

A combination of two or more types of inheritance. In C#, achieved using interfaces along with classes.

interface IA { }
class Base { }
class Derived : Base, IA { }
    

Note: C# allows single, multilevel, hierarchical, and hybrid inheritance using interfaces, but not direct multiple class inheritance.

Difference Between Encapsulation and Abstraction?

Encapsulation vs Abstraction

Encapsulation

  • Encapsulation is about hiding data and protecting it from outside access.
  • It bundles data and methods into a single unit (e.g., a class).
  • Achieved using access modifiers like private, protected, etc.
  • Controls how data is accessed or modified.
class Person {
    private int age; // hidden data

    public void SetAge(int value) { // controlled access
        if (value >= 0) age = value;
    }
}
    

Abstraction

  • Abstraction is about hiding complexity and showing only essential features.
  • Lets you focus on what something does rather than how it works.
  • Achieved using abstract classes and interfaces.
abstract class Animal {
    public abstract void MakeSound(); // only essential behavior shown
}
    

Summary

Encapsulation Abstraction
Hides internal data Hides implementation complexity
Protects the data Simplifies the design

Encapsulation = hiding data
Abstraction = hiding complexity

Can you override private methods in C#?

Overriding Private Methods in C#

No. In C#, private methods cannot be overridden because they are not visible to derived classes. A method must be accessible (protected/public) and marked as virtual, abstract, or override to support overriding.

Example (Not Allowed)

class Base {
    private void DoThing() { }
}

class Derived : Base {
    private void DoThing() { } 
}
    

Correct Way (Use protected + virtual)

class Base {
    protected virtual void DoThing() { }
}

class Derived : Base {
    protected override void DoThing() { }
}
    

If you need to override behavior, make the method protected and virtual.

What are access modifiers

Access Modifiers Explained

Access modifiers are keywords used in object-oriented programming to define how and where class members (fields, methods, properties, etc.) can be accessed. They are essential for implementing encapsulation and controlling visibility.

Common Access Modifiers in C#

1. public

Accessible from anywhere in the program. Used for methods or properties meant to be widely available.

2. private

Accessible only within the same class. Most restrictive and commonly used for data hiding.

3. protected

Accessible within the same class and its derived classes.

4. internal

Accessible anywhere within the same assembly/project.

5. protected internal

Accessible within the same assembly or in derived classes outside the assembly.

6. private protected

Accessible only within the same class or its derived classes in the same assembly.


Example in C#


public class Person
{
    private string name;          // Only inside this class
    protected int age;            // This class + derived classes
    internal string address;      // Same assembly
    public string GetInfo()       // Everywhere
    {
        return $"{name}, {age}, {address}";
    }
}

Access modifiers help control data access, improve maintainability, and enhance security.

Encapsulation Example in C#

Encapsulation Example in C#

This example shows how private fields are protected and accessed only through public methods (getters/setters):


public class BankAccount
{
    // Private field: cannot be accessed directly from outside the class
    private decimal balance;

    // Public method to deposit money (with controlled access)
    public void Deposit(decimal amount)
    {
        if (amount > 0)
        {
            balance += amount;
        }
    }

    // Public method to withdraw money (example of validation)
    public void Withdraw(decimal amount)
    {
        if (amount > 0 && amount <= balance)
        {
            balance -= amount;
        }
    }

    // Public getter for balance (read-only access)
    public decimal GetBalance()
    {
        return balance;
    }
}

// Usage example:
var account = new BankAccount();
account.Deposit(100);
account.Withdraw(40);
Console.WriteLine(account.GetBalance()); // Output: 60

This demonstrates encapsulation because the balance field is hidden from direct access, and all interactions with it go through controlled methods.

How Encapsulation Improves Security ?

How Encapsulation Improves Security

Encapsulation is one of the core principles of object-oriented programming. It enhances security in several important ways:

1. Data Hiding

Encapsulation restricts direct access to an object’s internal data. By making fields private or protected, external code cannot modify data in unexpected or harmful ways.

2. Controlled Access

Access to data is provided only through well-defined public methods (getters, setters, and other interfaces). This ensures that any interaction with the internal state follows rules you define.

3. Preventing Unauthorized Use

Since internal implementation details are hidden, attackers or misbehaving code cannot exploit or depend on those details. This reduces the risk of security vulnerabilities.

4. Improved Maintainability and Integrity

By isolating internal logic, you prevent other parts of the program from breaking it. This preserves the integrity of your data and reduces the chance of introducing security flaws during updates.

5. Reduces Attack Surface

Only essential operations are exposed publicly. A smaller interface means fewer entry points for potential attacks.


In summary: Encapsulation enhances security by hiding data, controlling access, protecting integrity, and minimizing exposure of internal logic.

C# Destructors

C# Destructors Explained

What is a Destructor?

A destructor is a special method in C# used to clean up resources when an object is no longer needed or is about to be destroyed. Destructors are automatically called by the garbage collector.

Key Points About Destructors

  • Called automatically before an object is destroyed.
  • Cannot take parameters.
  • Does not return any value.
  • Named with a tilde (~) before the class name.
  • Used to release resources like memory, files, or database connections.

Syntax Example

using System;

class Car
{
    public string Model;

    // Constructor
    public Car(string model)
    {
        Model = model;
        Console.WriteLine($"{Model} object created.");
    }

    // Destructor
    ~Car()
    {
        Console.WriteLine($"{Model} object destroyed.");
    }
}

class Program
{
    static void Main()
    {
        Car myCar = new Car("BMW");
        Car anotherCar = new Car("Audi");

        Console.WriteLine("End of Main method.");
    }
}

    

Possible Output

BMW object created.
Audi object created.
End of Main method.
BMW object destroyed.
Audi object destroyed.
    

Constructor vs Destructor

Feature Constructor Destructor
Purpose Initialize object Clean up before object is destroyed
Parameters Can have parameters Cannot have parameters
Return Type None None
Call Automatically when object is created Automatically when object is destroyed (GC)
Naming Same as class ~ClassName

C# Constructors

C# Constructors Explained

What is a Constructor?

A constructor is a special method in C# used to initialize objects of a class. It is automatically called when an object is created. Constructors typically set initial values for the object's fields or perform setup tasks.

Key Points About Constructors

  • Constructor has the same name as the class.
  • It does not have a return type, not even void.
  • Automatically called when an object is created.
  • A class can have multiple constructors with different parameters (constructor overloading).
  • Ensures that the object starts in a valid state.

Types of Constructors in C#

  • Default Constructor: No parameters. Sets default values.
  • Parameterized Constructor: Takes arguments to initialize the object.
  • Static Constructor: Initializes static members. Called once before the first object.

Example: Parameterized Constructor

using System;

class Car
{
    public string Model;
    public string Color;

    // Constructor
    public Car(string model, string color)
    {
        Model = model;
        Color = color;
        Console.WriteLine("Car object created!");
    }

    public void DisplayInfo()
    {
        Console.WriteLine($"Model: {Model}, Color: {Color}");
    }
}

class Program
{
    static void Main()
    {
        // Creating an object calls the constructor
        Car myCar = new Car("BMW", "Red");
        myCar.DisplayInfo();
    }
}

    

Output

Car object created!
Model: BMW, Color: Red
    

What is Abstraction?

What is Abstraction?

What is Abstraction?

Abstraction is an important concept in Object-Oriented Programming (OOP). It focuses on hiding complex implementation details and showing only the essential features of an object.

Simple Definition: Abstraction = Show only what is necessary, hide the rest.

Real-Life Example

Think about driving a car:

  • You press the brake → the car stops
  • You don’t see hydraulic pressure, brake pads, or piston mechanics

The system hides the complex details and gives you a simple interface.

How Abstraction Works in Programming

Abstraction is achieved by:

  • Abstract Classes
  • Interfaces

Abstraction Using Abstract Class (C# Example)


// Abstract class example
abstract class Animal
{
    public abstract void MakeSound();  // Abstract method
    public void Sleep()                // Normal method
    {
        Console.WriteLine("Sleeping...");
    }
}

class Dog : Animal
{
    public override void MakeSound()
    {
        Console.WriteLine("Bark");
    }
}

Here, the abstract class hides the internal process of how the dog makes a sound. The programmer only sees MakeSound().

Abstraction Using Interface (C# Example)


interface IVehicle
{
    void Start();
    void Stop();
}

class Car : IVehicle
{
    public void Start()
    {
        Console.WriteLine("Car starting...");
    }
    public void Stop()
    {
        Console.WriteLine("Car stopping...");
    }
}

The interface defines WHAT must be done, not HOW. Each class provides its own implementation.

Why Use Abstraction?

  • Reduces code complexity
  • Keeps implementation details hidden
  • Improves security
  • Increases maintainability
  • Allows focus on essential functionality

Conclusion

Abstraction helps simplify complex systems by exposing only the necessary parts. It is key to building clean, understandable, and scalable software.

What is Polymorphism?

Polymorphism in C# - Detailed Explanation

Polymorphism in C#

Polymorphism in C# allows methods to have different implementations depending on the object type. The same method call behaves differently based on the actual object at runtime or depending on overloads at compile time.

Simple definition: Polymorphism = One method → Many behaviors.

Types of Polymorphism in C#

1. Compile-Time Polymorphism (Method Overloading)

This happens when multiple methods share the same name but use different parameters.

// C# Method Overloading Example
class Calculator
{
    public int Add(int a, int b)
    {
        return a + b;
    }

    public double Add(double x, double y)
    {
        return x + y;
    }

    public string Add(string a, string b)
    {
        return a + b;
    }
}

Here the method Add() works differently depending on what type of arguments you pass.


2. Runtime Polymorphism (Method Overriding)

Achieved using:

  • virtual keyword (parent class)
  • override keyword (child class)

// C# Runtime Polymorphism Example
class Animal
{
    public virtual void Speak()
    {
        Console.WriteLine("Animal sound");
    }
}

class Dog : Animal
{
    public override void Speak()
    {
        Console.WriteLine("Dog barks");
    }
}

class Cat : Animal
{
    public override void Speak()
    {
        Console.WriteLine("Cat meows");
    }
}
// Main Program
Animal a1 = new Dog();
Animal a2 = new Cat();

a1.Speak();  // Dog barks
a2.Speak();  // Cat meows

Even though the reference type is Animal, the overridden method in the child class is called.


Polymorphism With Abstract Classes

// Abstract Class Example
abstract class Shape
{
    public abstract void Draw();
}

class Circle : Shape
{
    public override void Draw()
    {
        Console.WriteLine("Drawing a Circle");
    }
}

class Square : Shape
{
    public override void Draw()
    {
        Console.WriteLine("Drawing a Square");
    }
}

// Using Polymorphism
Shape s = new Circle();
s.Draw();  // Drawing a Circle

Using an abstract class ensures that every child MUST implement the method.


Polymorphism Using Interfaces

// Interface Polymorphism Example
interface IPayment
{
    void Pay();
}

class CreditCard : IPayment
{
    public void Pay()
    {
        Console.WriteLine("Paid using Credit Card");
    }
}

class PayPal : IPayment
{
    public void Pay()
    {
        Console.WriteLine("Paid using PayPal");
    }
}

// Using Interface Polymorphism
IPayment payment = new PayPal();
payment.Pay();  // Paid using PayPal

Real-World C# Example

// Real-world example: Notification System
abstract class Notification
{
    public abstract void Send(string message);
}

class Email : Notification
{
    public override void Send(string message)
    {
        Console.WriteLine("Sending Email: " + message);
    }
}

class SMS : Notification
{
    public override void Send(string message)
    {
        Console.WriteLine("Sending SMS: " + message);
    }
}
// Using Polymorphism
List<Notification> channels = new List<Notification>()
{
    new Email(),
    new SMS()
};

foreach (var channel in channels)
{
    channel.Send("Hello User!");
}

Each class implements Send() differently, but the method call stays the same.


Advantages of Polymorphism in C#

  • Makes code flexible and extendable
  • Supports loose coupling
  • Improves code readability and reusability
  • Allows the same interface for different implementations

Conclusion

Polymorphism in C# allows you to write generic code that works with different object types. The correct method is selected based on the actual object at compile time (overloading) or at runtime (overriding).

Friday, 14 November 2025

What is Inheritance in OOP?

What is Inheritance in OOP?

What is Inheritance in OOP?

Inheritance is a fundamental principle of Object-Oriented Programming (OOP). It allows a class to acquire properties and methods from another class.

Inheritance = Reusing code by creating a new class from an existing class

Why Use Inheritance?

  • ✔ Reuse existing code
  • ✔ Reduce duplication
  • ✔ Easier to maintain code
  • ✔ Create hierarchical relationships
  • ✔ Supports polymorphism

Real-Life Example

A Car is a type of Vehicle. A car inherits all common features of a vehicle (like wheels and speed control) and adds its own features (like air conditioning and radio).
Vehicle → base class (parent)
Car → derived class (child)

C# Example of Inheritance


class Vehicle
{
    public int Speed;

    public void Move()
    {
        Console.WriteLine("Vehicle is moving");
    }
}

class Car : Vehicle    // Car inherits Vehicle
{
    public string Color;

    public void Honk()
    {
        Console.WriteLine("Car is honking");
    }
}

    

Usage:


Car myCar = new Car();
myCar.Speed = 80;    // inherited from Vehicle
myCar.Move();        // inherited method
myCar.Color = "Red"; // property from Car class
myCar.Honk();        // method from Car class

    

Key Points to Remember

  • The child class inherits fields and methods from the parent class.
  • The child class can add its own properties and methods.
  • Supports method overriding using virtual and override.
  • Helps in code reuse, structure, and polymorphism.

What is Encapsulation?

What is Encapsulation?

What is Encapsulation?

Encapsulation is one of the key principles of Object-Oriented Programming (OOP). It refers to the practice of wrapping data (variables) and methods (functions) into a single unit and restricting direct access to some of an object's components.

Encapsulation = Data Hiding + Controlled Access

Why Use Encapsulation?

  • ✔ Protects data from accidental modification
  • ✔ Controls how data is accessed
  • ✔ Improves code security and maintainability
  • ✔ Keeps implementation details hidden

Real-Life Example

Think of a medicine capsule. You cannot directly see or touch the powder inside; you just use the capsule. Similarly, encapsulation hides internal data and allows controlled interaction.

C# Example of Encapsulation


class BankAccount
{
    private double balance;  // hidden data

    public void Deposit(double amount)
    {
        if (amount > 0)
            balance += amount;
    }

    public double GetBalance()
    {
        return balance;
    }
}

    

In this example:

  • private keyword hides the variable balance.
  • Access is controlled using methods like Deposit() and GetBalance().

Key Points to Remember

  • Encapsulation hides internal data.
  • Uses access modifiers like private, public, and protected.
  • Improves code security, reliability, and flexibility.

Difference Between Class and Object ?

Difference Between Class and Object

Difference Between Class and Object ?

What is a Class?

A class is a blueprint or template used to create objects. It defines the data (fields) and behavior (methods) that the objects will have. A class itself does not occupy memory until an object is created.

C# Example of a Class:


class Car
{
    public string Color;
    public int Speed;

    public void Drive()
    {
        Console.WriteLine("The car is driving.");
    }
}

    

What is an Object?

An object is an instance of a class. It is the real, usable entity created from the class. An object occupies memory and stores actual values for the fields defined in the class.

C# Example of an Object:


Car myCar = new Car();
myCar.Color = "Red";
myCar.Speed = 80;
myCar.Drive();

    

Comparison Table

Feature Class Object
Definition Blueprint or template Instance of a class
Memory Does not occupy memory Occupies memory
Purpose Defines structure and behavior Holds real data and performs actions
Example Car myCar, car1, car2
Type Logical entity Physical entity (in memory)

Simple Analogy

A class is like a recipe for a cake.
An object is the actual cake made using that recipe.

One recipe can make many cakes, each different in flavor or decoration—just like many objects can be created from one class.

What is an object?

What is an Object in OOP (C# Example)

What is an Object in OOP?

In object-oriented programming (OOP), an object is an instance of a class. A class is a blueprint, and an object is the actual usable form created from that blueprint. Objects contain data (attributes) and behaviors (methods).

Example in C#

Here is a simple class and object example:


class Car
{
    public string Color;
    public int Speed;

    public void Accelerate()
    {
        Speed += 10;
    }
}

Car myCar = new Car();
myCar.Color = "Red";
myCar.Speed = 60;

myCar.Accelerate();
Console.WriteLine(myCar.Speed);  // Output: 70

    

Objects in Memory

In C#, objects are stored in the heap, while the reference variable (like myCar) is stored on the stack. Each object has its own data and can call its own methods.

Thursday, 13 November 2025

Class

What is a Class in Object-Oriented Programming?

In the world of Object-Oriented Programming (OOP), a class is a fundamental concept. Think of it as a blueprint, a template, or a prototype from which objects are created. It's not an object itself, but rather the definition of what an object of a certain type will look like and how it will behave.


The Blueprint Analogy

Imagine you want to build many houses. You wouldn't draw a completely new plan for each house. Instead, you'd create a single, detailed blueprint for a particular style of house – let's say a "Family Home."

  • The Blueprint (Class): This blueprint defines everything about a Family Home: it has 3 bedrooms, 2 bathrooms, a kitchen, a living room, a total area of 1500 sq ft, and methods for "opening the door" or "turning on the lights." It describes the structure and potential actions.
  • The Actual Houses (Objects): From this single blueprint, you can build many individual houses. Each house is a distinct, physical entity based on that same blueprint. One house might have a red door, another a blue door, but both follow the "Family Home" blueprint.

In OOP, the class is that blueprint, and the individual objects are the actual houses built from it.


Key Components of a Class

A class typically consists of two main types of members:

  1. Attributes (Data/Properties/Fields):
    These are variables that define the characteristics or state of an object. In our "Family Home" example, attributes would be numberOfBedrooms, numberOfBathrooms, squareFootage, colorOfDoor, etc.
    * Example (in a Car class): make, model, year, color, speed.
  2. Methods (Behavior/Functions):
    These are functions that define what an object can do or what can be done to it. For a "Family Home," methods might include openDoor(), turnOnLights(), heatHouse().
    * Example (in a Car class): startEngine(), accelerate(), brake(), turn().

Why Use Classes?

Classes bring several powerful benefits to programming:

  • Modularity: They allow you to break down complex systems into smaller, manageable, and self-contained units.
  • Code Reusability: Once a class is defined, you can create multiple objects from it without rewriting the same code. This saves time and reduces errors.
  • Organization: They provide a clear structure for your code, making it easier to understand, maintain, and debug.
  • Encapsulation: Classes help bundle data and the methods that operate on that data together,

Basics of OOPs

The Four Pillars of OOP

The Four Pillars of OOP: Building Blocks of Modern Code

Object-Oriented Programming (OOP) is a programming paradigm built around the concept of "objects," which can contain data and code to manipulate that data. It's a fundamental concept in many popular languages today, including Java, C++, Python, and C#.

Mastering OOP involves understanding its four foundational concepts, often referred to as the Four Pillars. These principles help developers create code that is more manageable, flexible, reusable, and secure.


1. Encapsulation

Encapsulation is the mechanism of bundling data (variables) and the methods (functions) that operate on that data into a single unit (a class).

  • Data Hiding: A key aspect is data hiding. Encapsulation lets you hide the internal state of an object from the outside world. This is often achieved by making variables private and providing public getters and setters (methods) to access or modify them.
  • Benefits: It protects data from accidental modification, making the code more robust and easier to maintain. You control how the data can be manipulated.

Analogy: Think of a smart phone. You can use the screen and buttons (public methods) to interact with it, but you can't directly access or mess with the complex internal circuitry and components (private data).


2. Abstraction

Abstraction is the concept of showing only essential information to the user and hiding the complex internal details.

  • Focus on 'What' over 'How': It allows you to define the expected behavior of an object without specifying how that behavior is achieved. Abstract classes and interfaces are common tools for implementing this.
  • Benefits: It simplifies complex systems by reducing the cognitive load on the programmer. Users only see what they need to interact with the object.

Analogy: When you drive a car, you use the steering wheel, accelerator, and brake (the abstract interface). You don't need to know the intricate mechanics happening inside the engine and transmission (the hidden implementation).


3. Inheritance

Inheritance is the mechanism where one class acquires the properties (fields) and behavior (methods) of another class.

  • Parent-Child Relationship: The class being inherited from is called the Parent (or Super/Base) class, and the new class is the Child (or Sub/Derived) class.
  • Code Reusability: It promotes code reusability because you don't have to write the same methods/fields multiple times. The Child class can reuse the Parent's code and also add its own unique features.
  • "Is-A" Relationship: Inheritance is best used to model an "Is-A" relationship (e.g., A Dog Is-A Mammal).

Analogy: Consider biological inheritance. A child inherits certain traits and characteristics from their parents, but they also develop their own unique traits.


4. Polymorphism

Polymorphism literally means "many forms." In OOP, it refers to the ability of an object or method to take on multiple forms or implementations.

  • Method Overloading: Defining multiple methods in the same class with the same name but different parameters.
  • Method Overriding: Defining a method in the Child class that has the same name and parameters as a method in its Parent class, allowing the Child to provide a specialized implementation.
  • Benefits: It makes the code flexible and allows a single interface to be used for a general class of actions.

Analogy: The "Speak" action. A Dog object, a Cat object, and a Human object might all have a speak() method, but the actual implementation (the "form") of that method will be different: a Dog barks, a Cat meows, and a Human talks.


Why Do These Pillars Matter?

These four pillars are not just theoretical concepts; they are practical tools that dictate the quality of your software:

  • Reliability: Encapsulation protects data integrity.
  • Clarity: Abstraction simplifies the user's view of a complex system.
  • Efficiency: Inheritance saves time by promoting code reuse.
  • Flexibility: Polymorphism allows a single action to behave differently depending on the context.

Understanding and applying these principles is crucial for any developer aiming to write clean, modular, and scalable object-oriented software.


Would you like me to elaborate on one of these pillars or provide a simple code example for a language like Python or Java?