Intern
What is the main idea of encapsulation in object-oriented programming?
sobes.tech AI
Answer from AI
Encapsulation is a mechanism that combines data (fields) and methods that work with this data into a single object (class), as well as hiding implementation details from the outside world.
Main ideas:
- Data hiding: The internal state of an object is hidden and accessible only through public methods. This prevents direct modification of data from outside and guarantees its integrity.
- Access control: Access to fields is done through methods (getters and setters), allowing the application of data validation logic when retrieving or modifying data.
- Manageability and support: Changing the internal implementation of a class does not affect code that uses this class if the public interface remains unchanged.
Example:
public class Account {
private double balance; // Data hiding
public Account(double initialBalance) {
if (initialBalance >= 0) {
this.balance = initialBalance;
} else {
this.balance = 0;
}
}
public double getBalance() { // Getter for data access
return balance;
}
public void deposit(double amount) { // Method to modify data
if (amount > 0) {
balance += amount;
}
}
public void withdraw(double amount) { // Method to modify data
if (amount > 0 && amount <= balance) {
balance -= amount;
}
}
}