🔥 Top Encapsulation Questions with Answers
- Get link
- X
- Other Apps
Q1. What is encapsulation in C#?
Answer:
Encapsulation means hiding internal data of a class and exposing controlled access through public methods or properties.
It binds data and behavior together to ensure data integrity and security.
✅ Example:
class Account
{
private double balance;
public void Deposit(double amount)
{
if (amount > 0)
balance += amount;
}
public double GetBalance()
{
return balance;
}
}
Here, the balance is hidden — you can’t directly modify it, only through methods.
Q2. Why is encapsulation important?
Answer:
Because it:
-
Prevents unauthorized access to data.
-
Makes code more secure and maintainable.
-
Allows validation logic before updating data.
-
Supports modularity (class is independent).
✅ Example:
public void SetAge(int age)
{
if (age >= 18)
this.age = age;
else
Console.WriteLine("Underage not allowed!");
}
Here, validation ensures data consistency.
Q3. How do you achieve encapsulation in C#?
Answer:
Encapsulation is achieved by:
-
Declaring variables as private.
-
Providing public getter and setter methods, or
-
Using C# properties.
✅ Example (with properties):
public class Employee
{
private int salary;
public int Salary
{
get { return salary; }
set
{
if (value >= 10000)
salary = value;
else
Console.WriteLine("Salary too low!");
}
}
}
Q4. What is the difference between encapsulation and abstraction?
| Encapsulation | Abstraction |
|---|---|
| Hides data (variables) | Hides implementation (methods) |
| Focuses on data protection | Focuses on simplifying usage |
Done using private, public | Done using abstract, interface |
| Example: private fields + getters/setters | Example: abstract class or interface |
✅ Example Difference:
// Encapsulation
private int balance;
// Abstraction
public abstract void Withdraw();
Q5. Can you give a real-world example of encapsulation?
Answer:
Yes — think of a bank ATM.
-
You can deposit or withdraw, but you can’t directly access the bank database.
-
You only interact with public methods of the ATM.
✅ Example:
public class BankAccount
{
private double balance;
public void Deposit(double amount)
{
balance += amount;
}
public void Withdraw(double amount)
{
if (amount <= balance)
balance -= amount;
else
Console.WriteLine("Insufficient balance!");
}
public double GetBalance()
{
return balance;
}
}
Q6. Can encapsulation exist without data hiding?
Answer:
No.
Encapsulation requires data hiding — that’s the main principle.
If you make all variables public, encapsulation is broken.
❌ Bad Example:
public class Student
{
public string Name; // anyone can modify
}
✅ Good Example:
private string Name;
public void SetName(string n) { Name = n; }
Q7. How do auto-implemented properties help encapsulation in C#?
Answer:
Auto-properties in C# simplify encapsulation by automatically creating a private backing field.
✅ Example:
public class Person
{
public string Name { get; set; } // Auto property
}
This is a shorthand for:
private string name;
public string Name
{
get { return name; }
set { name = value; }
}
Q8. How can you restrict setting a property in encapsulation?
Answer:
Use read-only or write-only properties.
✅ Read-only property:
public class Product
{
public int Id { get; } = 1001; // can only read
}
✅ Write-only property:
public class Secret
{
private string code;
public string Code
{
set { code = value; } // cannot read outside
}
}
Q9. Can encapsulation improve code reusability?
Answer:
Yes.
Encapsulated classes are independent and modular — you can easily reuse them without worrying about internal logic.
✅ Example:
A Logger class with encapsulated fields and public methods can be reused in multiple projects.
Q10. What happens if we don’t use encapsulation?
Answer:
Without encapsulation:
-
Data can be modified directly.
-
No validation can be enforced.
-
Code becomes unreliable, error-prone, and hard to maintain.
❌ Example:
public class Account
{
public double Balance; // anyone can set any value
}
Someone can do:
account.Balance = -5000; // invalid data!
Q11. What are “Properties” in C# and how are they used in encapsulation?
Answer:
Properties are special methods (getters/setters) that control access to private fields.
✅ Example:
public class Car
{
private int speed;
public int Speed
{
get { return speed; }
set
{
if (value > 0 && value <= 200)
speed = value;
else
Console.WriteLine("Invalid speed!");
}
}
}
They allow controlled data access — perfect encapsulation!
Q12. Can you achieve encapsulation without using classes?
Answer:
No.
Encapsulation in C# is achieved through classes or structs, as they bind data and methods together.
Q13. Can you show an example of encapsulation using a constructor?
Answer:
Yes. You can set private data safely through a constructor.
✅ Example:
public class Employee
{
private string name;
public Employee(string name)
{
if (!string.IsNullOrEmpty(name))
this.name = name;
else
Console.WriteLine("Name cannot be empty!");
}
public string GetName() => name;
}
Q14. What is the relationship between encapsulation and access modifiers?
Answer:
Encapsulation is implemented using access modifiers:
-
private— hides data -
public— allows access -
protected— allows subclass access -
internal— allows access within assembly
✅ Example:
class Demo
{
private int a; // hidden
public int b; // open
protected int c; // accessible in derived class
}
Q15. Is encapsulation possible in structs in C#?
Answer:
Yes.
Structs can have private fields and public properties — just like classes.
✅ Example:
public struct Point
{
private int x;
public int X
{
get { return x; }
set { x = value; }
}
}
✅ Quick Summary Table
| Concept | Implementation | Example |
|---|---|---|
| Hide Data | private fields | private int balance; |
| Controlled Access | Getter/Setter methods | SetBalance(), GetBalance() |
| Properties | Encapsulate field automatically | public int Salary { get; set; } |
| Validation | Add conditions in setter | if (value > 0) salary = value; |
| Access Modifiers | Limit visibility | private, public, protected |
- Get link
- X
- Other Apps
Comments
Post a Comment