Junior — Middle
Explain the concept of encapsulation in object-oriented programming and why it is important?
sobes.tech AI
Answer from AI
Encapsulation is a principle of object-oriented programming that involves hiding the internal implementation of an object and providing access to data only through specific methods (getters and setters). This helps protect the object's state from incorrect modifications and reduces component coupling.
Why is this important:
- It provides control over data modification.
- It simplifies support and modification of code, as internal details are hidden.
- It enhances the security and reliability of the program.
Example in C#:
class User {
private string password; // hidden field
public void SetPassword(string pwd) {
if (pwd.Length >= 8) {
password = pwd;
} else {
throw new ArgumentException("Password is too short");
}
}
public bool CheckPassword(string pwd) {
return password == pwd;
}
}