Methods and encapsulation in OOP
Sat, 07 Dec 2024
Encapsulation is one of the fundamental principles of Object-Oriented Programming (OOP). It means bundling the data (fields/variables) and the methods (functions) that operate on the data into a single unit (class). It also restricts direct access to some of an object's components, which is a way of achieving data hiding.
Think of encapsulation as a protective shield that keeps the data safe within a class and only allows controlled access to it.
Key Features of Encapsulation: Data Hiding: The internal state of an object is hidden from the outside world. Only specific methods (getters and setters) can access or modify it. Improved Security: By restricting access to sensitive data, you can prevent accidental or unauthorized changes. Easier Maintenance: Changes in the internal implementation of a class do not affect code that uses it. Better Control: You can define how the data should be read or written by using methods. How to Achieve Encapsulation in Java Encapsulation in Java is implemented using:
Private Access Modifier: Declare the class variables (fields) as private so they can't be accessed directly from outside the class. Public Getter and Setter Methods: Provide public methods to get and update the values of private fields. Example of Encapsulation:
Copy code
class BankAccount {
// Private fields
private String accountHolderName;
private double balance;
// Constructor to initialize fields
public BankAccount(String accountHolderName, double initialBalance) {
this.accountHolderName = accountHolderName;
this.balance = initialBalance;
}
// Getter method for accountHolderName
public String getAccountHolderName() {
return accountHolderName;
}
// Setter method for accountHolderName
public void setAccountHolderName(String accountHolderName) {
this.accountHolderName = accountHolderName;
}
// Getter method for balance
public double getBalance() {
return balance;
}
// Method to deposit money (controlled access)
public void deposit(double amount) {
if (amount > 0) {
balance += amount;
} else {
System.out.println("Invalid deposit amount");
}
}
// Method to withdraw money (controlled access)
public void withdraw(double amount) {
if (amount > 0 && amount <= balance) {
balance -= amount;
} else {
System.out.println("Invalid withdrawal amount");
}
}
}
public class Main {
public static void main(String[] args) {
// Creating a BankAccount object
BankAccount account = new BankAccount("Sakib", 5000);
// Accessing data via methods
System.out.println("Account Holder: " + account.getAccountHolderName());
System.out.println("Initial Balance: " + account.getBalance());
// Updating data using methods
account.deposit(1000);
System.out.println("Balance after deposit: " + account.getBalance());
account.withdraw(2000);
System.out.println("Balance after withdrawal: " + account.getBalance());
}
}
Advantages of Encapsulation: Protects Data: By making fields private, you control how they are accessed or modified. Increases Flexibility: You can change the internal implementation without affecting the external code. Improves Readability: Encapsulation helps in organizing code and separating responsibilities. Facilitates Validation: You can validate data inside setter methods before modifying fields.
In Java, methods are like actions or behaviors that objects can perform. They are blocks of code designed to do specific tasks. Think of them as instructions you can call to perform an operation, such as adding two numbers, displaying a message, or modifying object properties.
Key Features of Methods: Encapsulation: Methods are part of classes and help in hiding the internal details of an object. Reusability: You can write a method once and use it multiple times, which saves time and reduces errors. Modularity: Methods divide your program into smaller chunks, making it easier to read and maintain.
class Calculator {
public int add(int a, int b) { // Method to add two numbers
return a + b;
}
}
public class Main {
public static void main(String[] args) {
Calculator calc = new Calculator(); // We are Creating an object
int result = calc.add(5, 3); // Now we are calling the method
System.out.println("Sum: " + result); // Output: Sum: 8
}
}
This is a comment 1.
This is a comment 2.