Encapsulation and Abstraction in C#
# CHAPTER 17
Encapsulation and Abstraction
1. Introduction
We have covered two pillars of OOP: Inheritance and Polymorphism. Now we focus on the remaining two: Encapsulation and Abstraction. These concepts are about security and simplicity. Encapsulation protects your data from being corrupted, while Abstraction hides complex logic so other developers don't have to worry about how things work behind the scenes.2. Learning Objectives
By the end of this chapter, you will be able to:-
Implement Encapsulation using
privatefields and public Properties.
- Understand the concept of Data Hiding.
-
Implement Abstraction using
abstractclasses and methods.
3. Encapsulation: Data Hiding
Imagine aBankAccount class. If the balance variable is public, anyone can write account.balance = -1000000;. This is disastrous.
Encapsulation dictates that internal data should be private (hidden). The only way to interact with that data is through controlled, public methods or Properties that contain validation logic.
4. Abstraction: Hiding Complexity
Abstraction focuses on *what* an object does, hiding *how* it does it. When you hit the brakes in your car, you don't need to know the hydraulic fluid pressure mathematics; you just need the car to stop.In C#, we achieve this using the abstract keyword.
5. Abstract Classes and Methods
An Abstract Class is a restricted class that cannot be instantiated (you cannot usenew on it). It exists solely to act as a base class for other classes to inherit from.
An Abstract Method is a method that has no body. It *forces* the child class to provide the implementation.
6. Why use Abstraction?
Abstraction allows you to define a strict contract. If you are the Lead Architect on a team, you can create an abstractDatabaseConnection class with an abstract Connect() method. You then assign your junior developers to write SqlServerConnection and MongoDbConnection. The compiler will *guarantee* that both of their classes have a Connect() method, ensuring standard architecture across the project.
7. Common Mistakes
-
Writing logic in an abstract method: Abstract methods cannot have curly braces
{}. They just end in a semicolon. Example:public abstract void DoWork();
-
Forgetting
override: When a derived class implements an abstract method, it must use theoverridekeyword.
8. Best Practices
-
Default to making all class fields
privateand exposing them only via Properties.
-
Use Abstract classes when you have some shared logic (like the
Displaymethod above) but want to force child classes to implement specific missing pieces.
9. Exercises
-
1.
Create a
Userclass with a private_passwordfield. Create a public methodSetPassword(string pwd)that only updates the password if it is longer than 6 characters.
-
2.
Create an abstract class
Vehiclewith an abstract methodHonkHorn(). Create aTruckclass that implements it.
10. MCQs with Answers
What is the primary purpose of Encapsulation?
Which access modifier is used to hide fields for Encapsulation?
How do external classes safely interact with encapsulated private fields?
What does Abstraction focus on?
new AbstractClass())?
a) Yes b) No
Answer: b) No
What MUST a child class do if it inherits an Abstract method?
Which keyword is required when implementing an abstract method in the child class?
If a class has at least one Abstract method, the class itself MUST be marked as:
public int Age { get; set; }) an example of Encapsulation?
a) Yes, the compiler generates a hidden private backing field behind the scenes b) No, because it is public
Answer: a) Yes
11. Interview Questions
- Q: Explain the difference between Abstraction and Encapsulation.
- Q: Can an abstract class have a constructor in C#? (Answer: Yes, it can have a constructor to initialize its own fields, which is called when the derived class is instantiated).
12. Summary
Encapsulation acts as a protective shield for your object's internal data, usingprivate fields and public Properties. Abstraction acts as a simplification tool, hiding complex logic behind clean contracts using abstract classes and methods, ensuring consistency across large applications.