Use Inheritance, Polymorphism and Encapsulation in C#

Use Inheritance, Polymorphism and Encapsulation in C#

Object-oriented programming (OOP) is a paradigm that makes the development and maintenance of software quite easier by modeling it around objects. Three of the core pillars of OOP include inheritance, polymorphism, and encapsulation. The blog will explore how to leverage these principles effectively within C# for the betterment of robust, reusable, and maintainable applications.

1. Understanding Inheritance

Inheritance allows a class known as the derived or child class to take properties and methods of another class called the base or parent class. This fosters code reusing and creates a hierarchical dependency among classes.

How to Implement Inheritance in C#

To inherit use the colon : symbol followed by the base class name.

The derived class is allowed to access both public as well as protected members of the base class.

  Example

// Base class

public class Animal

public string Name { get; set; }


    public void Eat()

    {

        Console.WriteLine($"{Name} is eating.");

    }

}

//Derived class

public class Dog : Animal

{

    public void Bark()

Console.WriteLine($"{Name} is barking.");

}

}

class Program

static void Main()

    {

        Dog dog = new Dog();

        dog.Name = "Buddy";

        dog.Eat(); // Inherited from Animal

        dog.Bark(); // Defined in Dog

Reusability: The frequent functionality is available in one place at the base class.

Readability: Logical relationships between classes are more transparent.

mts 

2. Polymorphism

You can use single interface representing different types of objects, by polymorphism. This is possible in C# through method overriding and method overloading.

How to Use Polymorphism in C#

1. Method Overriding: Designate a base class that contains a method and then allow derived classes to override those methods of the base class for specific implementation.

Make use of the virtual keyword in the base class.

Make use of the override keyword in the derived class.

   2. Method Overloading: Declare several methods with the same name but different lists of parameters in the same class.

 Example: Method Overriding

public class Animal

{

    public virtual void Speak()

{

    Console.WriteLine("The animal makes a sound.");

}

}


public class Dog : Animal

public override void Speak()

    {

        Console.WriteLine("The dog barks.");

    }

}

class Program

{

    static void Main()

    {

        Animal animal = new Animal();

animal.Speak();


animal dog = new Dog(); // Polymorphic behavior

        dog.Speak();

    }

}

Example: Method Overloading

public 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));       // Calls int version

Console.WriteLine(calc.Add(2.5, 3.5)); // Calls double version

    }

}

//

//

// Benefits

Flexibility: The same method name can serve different purposes.

Extensibility: New behaviors can be introduced without modifying existing code.

------------------------------------------------

3. Learing Encapsulation

Data encapsulation bundles data (fields) and methods or functions that operate on the data in a single unit, usually a class. It limits direct access to some of the object's components, which is crucial for maintaining data integrity.

How to Apply Encapsulation in C#

1. Using Access Modifiers for Field Hiding

access modifier attribute

2. Public Properties with get and set accessors

The accessors are, in fact, optional.


Example

public class BankAccount

private double balance;

    public double Balance

    {

        get { return balance; }

        private set { balance = value; }

    }


public void Deposit(double amount)

    {

        if (amount > 0)

        {

            balance += amount;

            Console.WriteLine($\"Deposited: {amount}\");

        }

    }


    public void Withdraw(double amount)

if (amount > 0 && amount <= balance)

        {

            balance -= amount;

            Console.WriteLine($"Withdrew: {amount}");

        }

    else

Console.WriteLine("Invalid withdrawal amount.");

        }

    }

}


class Program

{

    static void Main()

    {

        BankAccount account = new BankAccount();

        account.Deposit(1000);

withdraw(500);

Console.WriteLine($ "Remaining Balance: {account.Balance}");

        }

    }

Important Benefits

Data Security: It denies illegal or invalid access to confidential data.

Access Control: It offers verification or additional logic before modification of data.

Through inheritance, polymorphism, and encapsulation, you can develop modular and scalable software solutions. Here is a simple real-world example:


Real-World Example

abstract public class Employee

END

public string Name { get; set; }

    public abstract void CalculateSalary();

}


// Derived class 1

public class FullTimeEmployee : Employee

{

    public override void CalculateSalary()

    {

Console.WriteLine($"{Name}'s salary is computed based on fixed monthly rate.");

    }

}


// Derived class 2

public class PartTimeEmployee : Employee

public override void CalculateSalary()

    {

        Console.WriteLine($"{Name}'s salary is computed on an hour-to-hour basis.");

    }

}


// Encapsulation Example

public class Payroll

{

    private List<Employee> employees = new List<Employee>();

END


public void AddEmployee(Employee employee)

    {

        employees.Add(employee);

    }


public void ProcessPayroll()

    {

        foreach (var employee in employees)

        {

            employee.CalculateSalary();

}

}

class Program

{

    static void Main()

var fullTime = new FullTimeEmployee { Name = "John"};

            var partTime = new PartTimeEmployee { Name = "Jane"};


            Payroll payroll = new Payroll();

            payroll.AddEmployee(fullTime);

}

payroll.AddEmployee(partTime);


payroll.ProcessPayroll();

    }

}

Conclusion

Mastering inheritance, polymorphism, and encapsulation in C# lets you write clean, maintainable, and efficient code. Beyond just code reusability and flexibility, these principles ensure that your applications are scalable, easy to debug, and maintainable. Practice the code above, and soon you'll see what the power of OOP is all about.

More Details for programming knowledge link : 

Summary

Best top 5 Laptops for programming 

Amazon link: https://www.howtotech.in/search/label/Amazon%20Offers?m=1

Tags

Post a Comment

0 Comments
* Please Don't Spam Here. All the Comments are Reviewed by Admin.