C Sharp OOPS
C Sharp OOPS
Here are real-time examples that demonstrate the core Object-Oriented Programming (OOP) principles in C#,
including Encapsulation, Abstraction, Inheritance, Polymorphism, Interfaces, and Abstract Classes.
Explanation: The balance variable is encapsulated inside the BankAccount class and cannot be accessed
directly. Access is controlled via methods Deposit , Withdraw , and GetBalance .
// Regular method
public void Display()
{
Console.WriteLine("Displaying Shape...");
}
}
Explanation: The Shape class is abstract and does not define how to calculate the area. The Circle and
Rectangle classes implement the Area() method, abstracting away the complexity of how the area is
computed.
Explanation: The Dog and Cat classes inherit from the Animal class, so they share common methods like
Eat() and Sleep() , but each can have their own unique methods like Bark() and Meow() .
Explanation: The MakeSound() method is overridden in the Dog and Cat classes. At runtime, the
appropriate MakeSound() method is called based on the object type ( Dog or Cat ), demonstrating
polymorphism.
Explanation: Both Document and Image classes implement the IPrintable interface and provide their
own implementation for the Print() method. The interface ensures both classes adhere to the contract to
implement the Print() method.
Explanation: The Shape class is abstract and contains an abstract method Area() , which is implemented
by the Circle and Square classes. This allows us to define common behavior (like Display() ) while
leaving the implementation of Area() to the derived classes.
Summary of Principles:
Encapsulation: Hides the internal state of objects and exposes only the necessary functionality (e.g.,
BankAccount ).
Abstraction: Hides implementation details and exposes essential features (e.g., Shape with abstract methods).
Inheritance: Promotes code reuse by allowing a class to inherit properties and methods from another
(e.g., Animal class).
Polymorphism: Enables methods to work with objects of different types (e.g., MakeSound() in different
animals).
Interface: Defines a contract that classes must follow (e.g., IPrintable interface).
Abstract Class: Provides a base class with both abstract and concrete methods (e.g., Shape with Area() ).
These examples showcase how fundamental OOP concepts are applied in real-world C# programming to improve
code organization, maintainability, and scalability.