Object-Oriented Programming (OOP) Classes and Objects Inheritance, Encapsulation, and Polymorphism Design principles like SOLID

Object-Oriented Programming (OOP) in C# Classes and Objects Answer: A class is a blueprint that defines properties and methods, while an object is an instance of a class. Example (C#): csharp using System; class Car { public string Brand; public string Model; public Car(string brand, string model) { Brand = brand; Model = model; } public void DisplayInfo() { Console.WriteLine($"{Brand} {Model}"); } } class Program { static void Main() { Car car1 = new Car("Toyota", "Corolla"); Car car2 = new Car("Honda", "Civic"); car1.DisplayInfo(); // Output: Toyota Corolla car2.DisplayInfo(); // Output: Honda Civic } } Inheritance Answer: Inheritance allows a child class to inherit properties and methods from a parent class, reducing code duplication. Example (C#): csharp using System; class Vehicle { public string Brand; public Vehicle(string brand) { Brand = brand; } public void Honk() { Console.WriteLine("Beep Beep!"); } } class Car : Vehicle { public string Model; public Car(string brand, string model) : base(brand) { Model = model; } } class Program { static void Main() { Car myCar = new Car("Ford", "Mustang"); Console.WriteLine(myCar.Brand); // Output: Ford myCar.Honk(); // Output: Beep Beep! } } Encapsulation Answer: Encapsulation restricts direct access to certain fields, ensuring data integrity using getters and setters. Example (C#): csharp using System; class BankAccount { private decimal balance; // Private field public BankAccount(decimal initialBalance) { balance = initialBalance; } public void Deposit(decimal amount) { if (amount > 0) { balance += amount; } } public decimal GetBalance() { return balance; } } class Program { static void Main() { BankAccount account = new BankAccount(1000); account.Deposit(500); Console.WriteLine(account.GetBalance()); // Output: 1500 } } Polymorphism Answer: Polymorphism allows different classes to share method names but implement different behaviors. Example (C# - Method Overriding): csharp using System; class Animal { public virtual void MakeSound() { Console.WriteLine("Some sound..."); } } class Dog : Animal { public override void MakeSound() { Console.WriteLine("Bark"); } } class Cat : Animal { public override void MakeSound() { Console.WriteLine("Meow"); } } class Program { static void Main() { Animal myDog = new Dog(); Animal myCat = new Cat(); myDog.MakeSound(); // Output: Bark myCat.MakeSound(); // Output: Meow } } SOLID Principles in C# S - Single Responsibility Principle (SRP) A class should have only one reason to change. Example: csharp class User { public string Name { get; set; } public string Email { get; set; } } class AuthService { public void Login(User user) { Console.WriteLine($"{user.Name} logged in!"); } } O - Open/Closed Principle (OCP) A class should be open for extension but closed for modification. Example: csharp abstract class Shape { public abstract double GetArea(); } class Rectangle : Shape { public double Width { get; set; } public double Height { get; set; } public override double GetArea() { return Width * Height; } } class Circle : Shape { public double Radius { get; set; } public override double GetArea() { return Math.PI * Radius * Radius; } } L - Liskov Substitution Principle (LSP) Subclasses should be able to replace the parent class without breaking the functionality. Example: csharp class Bird { public virtual string Fly() { return "Flying"; } } class Sparrow : Bird { } // Sparrow can fly class Ostrich : Bird { public override string Fly() { return "Can't fly"; // Ostrich correctly overrides flying behavior } } I - Interface Segregation Principle (ISP) A class should not be forced to implement unnecessary methods. Example: csharp interface IPrinter { void Print(); } interface IScanner { void Scan(); } class Printer : IPrinter { public void Print() { Console.WriteLine("Printing..."); } } class MultiFunctionPrinter : IPrinter, IScanner { public void Print() { Console.WriteLine("Printing..."); } public void Scan() { Console.WriteLine("Scanning..."); } } D - Dependency Inversion Principle (DIP) High-level modules should not depend on low-level modules but on abstractions. Example: csharp interface IPaymentProcessor { string ProcessPayment(decimal amount); } class PayPal : IPa

Mar 27, 2025 - 01:59
 0
Object-Oriented Programming (OOP) Classes and Objects Inheritance, Encapsulation, and Polymorphism Design principles like SOLID

Object-Oriented Programming (OOP) in C#

  1. Classes and Objects Answer: A class is a blueprint that defines properties and methods, while an object is an instance of a class.

Example (C#):

csharp

using System;

class Car
{
    public string Brand;
    public string Model;

    public Car(string brand, string model)
    {
        Brand = brand;
        Model = model;
    }

    public void DisplayInfo()
    {
        Console.WriteLine($"{Brand} {Model}");
    }
}

class Program
{
    static void Main()
    {
        Car car1 = new Car("Toyota", "Corolla");
        Car car2 = new Car("Honda", "Civic");

        car1.DisplayInfo(); // Output: Toyota Corolla
        car2.DisplayInfo(); // Output: Honda Civic
    }
}

  1. Inheritance Answer: Inheritance allows a child class to inherit properties and methods from a parent class, reducing code duplication.

Example (C#):

csharp

using System;

class Vehicle
{
    public string Brand;

    public Vehicle(string brand)
    {
        Brand = brand;
    }

    public void Honk()
    {
        Console.WriteLine("Beep Beep!");
    }
}

class Car : Vehicle
{
    public string Model;

    public Car(string brand, string model) : base(brand)
    {
        Model = model;
    }
}

class Program
{
    static void Main()
    {
        Car myCar = new Car("Ford", "Mustang");
        Console.WriteLine(myCar.Brand); // Output: Ford
        myCar.Honk(); // Output: Beep Beep!
    }
}

  1. Encapsulation Answer: Encapsulation restricts direct access to certain fields, ensuring data integrity using getters and setters.

Example (C#):

csharp

using System;

class BankAccount
{
    private decimal balance; // Private field

    public BankAccount(decimal initialBalance)
    {
        balance = initialBalance;
    }

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

    public decimal GetBalance()
    {
        return balance;
    }
}

class Program
{
    static void Main()
    {
        BankAccount account = new BankAccount(1000);
        account.Deposit(500);
        Console.WriteLine(account.GetBalance()); // Output: 1500
    }
}

  1. Polymorphism Answer: Polymorphism allows different classes to share method names but implement different behaviors.

Example (C# - Method Overriding):

csharp

using System;

class Animal
{
    public virtual void MakeSound()
    {
        Console.WriteLine("Some sound...");
    }
}

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

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

class Program
{
    static void Main()
    {
        Animal myDog = new Dog();
        Animal myCat = new Cat();

        myDog.MakeSound(); // Output: Bark
        myCat.MakeSound(); // Output: Meow
    }
}

  1. SOLID Principles in C# S - Single Responsibility Principle (SRP) A class should have only one reason to change.

Example:

csharp

class User
{
    public string Name { get; set; }
    public string Email { get; set; }
}

class AuthService
{
    public void Login(User user)
    {
        Console.WriteLine($"{user.Name} logged in!");
    }
}

O - Open/Closed Principle (OCP)
A class should be open for extension but closed for modification.

Example:

csharp

abstract class Shape
{
    public abstract double GetArea();
}

class Rectangle : Shape
{
    public double Width { get; set; }
    public double Height { get; set; }

    public override double GetArea()
    {
        return Width * Height;
    }
}

class Circle : Shape
{
    public double Radius { get; set; }

    public override double GetArea()
    {
        return Math.PI * Radius * Radius;
    }
}

L - Liskov Substitution Principle (LSP)
Subclasses should be able to replace the parent class without breaking the functionality.

Example:

csharp

class Bird
{
    public virtual string Fly()
    {
        return "Flying";
    }
}

class Sparrow : Bird { } // Sparrow can fly

class Ostrich : Bird
{
    public override string Fly()
    {
        return "Can't fly"; // Ostrich correctly overrides flying behavior
    }
}

I - Interface Segregation Principle (ISP)
A class should not be forced to implement unnecessary methods.

Example:

csharp

interface IPrinter
{
    void Print();
}

interface IScanner
{
    void Scan();
}

class Printer : IPrinter
{
    public void Print()
    {
        Console.WriteLine("Printing...");
    }
}

class MultiFunctionPrinter : IPrinter, IScanner
{
    public void Print()
    {
        Console.WriteLine("Printing...");
    }

    public void Scan()
    {
        Console.WriteLine("Scanning...");
    }
}

D - Dependency Inversion Principle (DIP)
High-level modules should not depend on low-level modules but on abstractions.

Example:

csharp

interface IPaymentProcessor
{
    string ProcessPayment(decimal amount);
}

class PayPal : IPaymentProcessor
{
    public string ProcessPayment(decimal amount)
    {
        return $"Paid {amount} via PayPal";
    }
}

class Order
{
    private readonly IPaymentProcessor _paymentProcessor;

    public Order(IPaymentProcessor paymentProcessor)
    {
        _paymentProcessor = paymentProcessor;
    }

    public string Checkout(decimal amount)
    {
        return _paymentProcessor.ProcessPayment(amount);
    }
}

class Program
{
    static void Main()
    {
        IPaymentProcessor paymentProcessor = new PayPal();
        Order order = new Order(paymentProcessor);
        Console.WriteLine(order.Checkout(100)); // Output: Paid 100 via PayPal
    }
}

Summary (C# OOP Assessment Answer)
✅ Classes & Objects: Define reusable blueprints for creating objects.
✅ Inheritance: Enables code reuse by deriving classes from a parent class.
✅ Encapsulation: Restricts access to internal details using private fields and public methods.
✅ Polymorphism: Allows different classes to share method names but execute different behaviors.
✅ SOLID Principles: Ensures scalable, maintainable, and flexible OOP design.

Would you like me to tailor an answer specifically for your upcoming assessment?