foreach-ui logo
codeLanguages
account_treeDSA

Quick Actions

quizlock Random Quiz
trending_uplock Progress
  • 1
  • 2
  • 3
  • 4
  • quiz
Java
  • Understand encapsulation and its importance
  • Learn to implement encapsulation with private fields
  • Master controlled data access

Encapsulation Principles in Java

Encapsulation is one of OOP's four pillars (alongside inheritance, polymorphism, and abstraction). It's about bundling data and methods together, then restricting direct access to that data.

What is Encapsulation?

Encapsulation hides an object's internal details and forces access through public methods. Think of it like a vending machine—you don't reach inside to grab a soda, you press buttons (methods) to get what you want.

Key Benefits:

  1. Data Protection: Prevents unauthorized access to sensitive data
  2. Flexibility: Internal implementation can change without affecting external code
  3. Maintainability: Easier to modify and maintain code
  4. Security: Controls how data is accessed and modified

Implementing Encapsulation

1. Private Fields

Make class fields private to hide them from external access.

public class BankAccount {
    private String accountNumber;
    private double balance;
    private String ownerName;
}

2. Public Methods for Access

Provide public methods to access and modify the private fields.

public class BankAccount {
    private String accountNumber;
    private double balance;
    private String ownerName;

    // Constructor
    public BankAccount(String accountNumber, String ownerName) {
        this.accountNumber = accountNumber;
        this.ownerName = ownerName;
        this.balance = 0.0;
    }

    // Getter methods (accessors)
    public String getAccountNumber() {
        return accountNumber;
    }

    public double getBalance() {
        return balance;
    }

    public String getOwnerName() {
        return ownerName;
    }

    // Setter methods (mutators)
    public void setOwnerName(String ownerName) {
        this.ownerName = ownerName;
    }
}

3. Controlled Data Modification

Use setter methods to validate data before setting it.

public void deposit(double amount) {
    if (amount > 0) {
        balance += amount;
    } else {
        throw new IllegalArgumentException("Deposit amount must be positive");
    }
}

public void withdraw(double amount) {
    if (amount > 0 && amount <= balance) {
        balance -= amount;
    } else {
        throw new IllegalArgumentException("Invalid withdrawal amount");
    }
}

Read-Only and Write-Only Properties

Read-Only Properties

Provide only getters, no setters.

public class Person {
    private final String ssn;  // Social Security Number - should never change
    
    public Person(String ssn) {
        this.ssn = ssn;
    }
    
    public String getSsn() {
        return ssn;
    }
    // No setSsn() method
}

Write-Only Properties

Provide only setters, no getters (rare but useful for passwords).

public class User {
    private String passwordHash;
    
    public void setPassword(String password) {
        this.passwordHash = hashPassword(password);
    }
    // No getPassword() method for security
}

Encapsulation Best Practices

1. Always Use Private Fields

// Good
private String name;

// Avoid
public String name;

2. Validate Data in Setters

public void setAge(int age) {
    if (age >= 0 && age <= 150) {
        this.age = age;
    } else {
        throw new IllegalArgumentException("Invalid age");
    }
}

3. Use Meaningful Method Names

// Good
public void increaseSalary(double percentage)
public boolean isEligibleForLoan()

// Avoid
public void doSomething(double x)
public boolean check()

4. Minimize Public Interface

Expose only what needs to be public. Keep implementation details private.

Common Encapsulation Patterns

Data Transfer Object (DTO)

public class UserDTO {
    private String username;
    private String email;
    
    public UserDTO(String username, String email) {
        this.username = username;
        this.email = email;
    }
    
    // Getters only - immutable
    public String getUsername() { return username; }
    public String getEmail() { return email; }
}

Builder Pattern

public class Computer {
    private final String cpu;
    private final int ram;
    private final int storage;
    
    private Computer(Builder builder) {
        this.cpu = builder.cpu;
        this.ram = builder.ram;
        this.storage = builder.storage;
    }
    
    public static class Builder {
        private String cpu;
        private int ram;
        private int storage;
        
        public Builder cpu(String cpu) { this.cpu = cpu; return this; }
        public Builder ram(int ram) { this.ram = ram; return this; }
        public Builder storage(int storage) { this.storage = storage; return this; }
        
        public Computer build() { return new Computer(this); }
    }
}

Encapsulation lets you protect your data and keep your code flexible. By hiding implementation details behind public methods, you can change how things work internally without breaking code that depends on your class. Start with private fields and expose only what's necessary through well-designed methods.

© 2026 forEach. All rights reserved.

Privacy Policy•Terms of Service