Java Learner logo

Module 5: Object-Oriented Programming (OOP) Fundamentals

Lesson focus

Encapsulation and Access Modifiers

Learn how to protect your data using encapsulation, private fields, and public getter and setter methods.

What is Encapsulation? Encapsulation is the practice of bundling an object's data (fields) and methods together within a class, and controlling access to that data from the outside world.

Data Hiding: A key part of encapsulation is data hiding. We achieve this by declaring the class's fields as private. A private member can only be accessed from within its own class.

Access Modifiers:

  • public: The member is accessible from anywhere.
  • private: The member is accessible only within its own class.
  • protected: The member is accessible within its own package and by subclasses.
  • default (no keyword): The member is accessible only within its own package.

Getters and Setters: To provide controlled access to private fields, we use public methods known as getters and setters.

  • Getter: A method that retrieves the value of a private field. By convention, it is named getFieldName() (or isFieldName() for booleans).
  • Setter: A method that modifies the value of a private field. It is named setFieldName(). Setters are crucial because they allow you to add validation logic before changing a field's value.

Benefits of Encapsulation:

  • Control: You control how the data in your objects is used and modified.
  • Security: You can protect your object from being put into an invalid state.
  • Flexibility: You can change the internal implementation of a class without breaking the code that uses it, as long as the public methods remain the same.

Mini-Exercise: Create a BankAccount class with a private balance field. Add a public getBalance() method. Add a public deposit(double amount) method that only adds positive amounts. Add a public withdraw(double amount) method that only allows withdrawals if the amount is positive and there are sufficient funds.

public class Student {
    private String name;
    private int age;

    // Getter for name
    public String getName() {
        return this.name;
    }

    // Setter for name
    public void setName(String name) {
        if (name != null && !name.isBlank()) {
            this.name = name;
        }
    }

    // Getter for age
    public int getAge() {
        return this.age;
    }

    // Setter for age with validation
    public void setAge(int age) {
        if (age > 0) {
            this.age = age;
        }
    }
}

Lesson quiz

Why should fields in a class generally be declared as `private`?

Next lesson →