Java Encapsulation

Private Variables, Getters, and Setters

Learning Goal

Students will understand how encapsulation protects data inside a class by using private instance variables and controlled access through getter and setter methods.

1. What Is Encapsulation?

Encapsulation is an object-oriented programming concept where the data inside a class is protected from direct outside access.

In Java, encapsulation usually means:

  1. Make instance variables private
  2. Use public getter methods to read values
  3. Use public setter methods to change values safely
Encapsulation helps protect an object’s data from being changed incorrectly.

2. Why Do We Use Encapsulation?

Encapsulation helps programmers:

Think of encapsulation like a vending machine. You do not reach directly inside the machine to grab a snack. Instead, you press buttons and the machine controls what happens.

3. Private Instance Variables

Instance variables store the data for an object. To protect them, we usually make them private.

public class Student {
    private String name;
    private int grade;
}

Because name and grade are private, they cannot be accessed directly from another class.

4. Why Not Make Variables Public?

A public variable can be changed directly from outside the class.

public class Student {
    public String name;
    public int grade;
}

Another class could do this:

Student s = new Student();
s.grade = -50;
This is a problem because a grade should not be negative.

Using encapsulation allows the class to control what values are allowed.

5. Getter Methods

A getter method allows another class to read the value of a private variable.

Getter methods usually:

public String getName() {
    return name;
}

Full Example

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

    public String getName() {
        return name;
    }

    public int getGrade() {
        return grade;
    }
}

6. Setter Methods

A setter method allows another class to change the value of a private variable.

Setter methods usually:

public void setName(String newName) {
    name = newName;
}

Example

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

    public void setName(String newName) {
        name = newName;
    }

    public void setGrade(int newGrade) {
        grade = newGrade;
    }
}

7. Setters Can Protect Data

One major reason to use setters is to check if a value is valid before changing the variable.

public void setGrade(int newGrade) {
    if (newGrade >= 0 && newGrade <= 100) {
        grade = newGrade;
    }
}

Example use:

Student s = new Student();

s.setGrade(95);   // valid
s.setGrade(-20);  // ignored
The object protects itself from bad data.

8. Complete Student Class Example

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

    public Student(String studentName, int studentGrade) {
        name = studentName;

        if (studentGrade >= 0 && studentGrade <= 100) {
            grade = studentGrade;
        } else {
            grade = 0;
        }
    }

    public String getName() {
        return name;
    }

    public int getGrade() {
        return grade;
    }

    public void setName(String studentName) {
        name = studentName;
    }

    public void setGrade(int studentGrade) {
        if (studentGrade >= 0 && studentGrade <= 100) {
            grade = studentGrade;
        }
    }
}

9. Using the Student Class

public class StudentRunner {
    public static void main(String[] args) {
        Student s1 = new Student("Maria", 90);

        System.out.println(s1.getName());
        System.out.println(s1.getGrade());

        s1.setGrade(98);
        System.out.println(s1.getGrade());

        s1.setGrade(-15);
        System.out.println(s1.getGrade());
    }
}

Output

Maria
90
98
98

The value stayed 98 because -15 was rejected by the setter.

10. Common Naming Pattern

Variable Getter Setter
name getName() setName(String name)
age getAge() setAge(int age)
score getScore() setScore(int score)
passing isPassing() setPassing(boolean passing)

For boolean variables, getters often start with is.

public boolean isPassing() {
    return passing;
}

11. The this Keyword with Setters

Sometimes the parameter has the same name as the instance variable.

private String name;

public void setName(String name) {
    this.name = name;
}

this.name refers to the instance variable.
name refers to the parameter.

The keyword this means “this object.”

12. Example Using this

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

    public Student(String name, int grade) {
        this.name = name;
        this.grade = grade;
    }

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

    public int getGrade() {
        return this.grade;
    }

    public void setName(String name) {
        this.name = name;
    }

    public void setGrade(int grade) {
        if (grade >= 0 && grade <= 100) {
            this.grade = grade;
        }
    }
}

13. Encapsulation Example: Bank Account

A bank account should not allow the balance to be changed directly.

Bad Design

public class BankAccount {
    public double balance;
}

This allows dangerous code:

BankAccount account = new BankAccount();
account.balance = -1000000;

Better Design

public class BankAccount {
    private double balance;

    public BankAccount(double startingBalance) {
        if (startingBalance >= 0) {
            balance = startingBalance;
        } else {
            balance = 0;
        }
    }

    public double getBalance() {
        return balance;
    }

    public void deposit(double amount) {
        if (amount > 0) {
            balance += amount;
        }
    }

    public void withdraw(double amount) {
        if (amount > 0 && amount <= balance) {
            balance -= amount;
        }
    }
}
Notice that there is no simple setBalance() method. Instead, the class uses deposit() and withdraw() to control how money changes.

14. Important Rule

Not every private variable needs a setter.

Sometimes a value should be read but not changed directly.

private int studentId;

public int getStudentId() {
    return studentId;
}

There may be no setStudentId() because the ID should not change after the object is created.

15. AP Computer Science A Connection

Encapsulation is important in AP Computer Science A because students are expected to understand:

Encapsulation is often used in AP CSA free-response questions.

16. Common Mistakes

Mistake 1: Making instance variables public

// Weak design
public int grade;

// Better design
private int grade;

Mistake 2: Forgetting the return type in a getter

// Incorrect
public getGrade() {
    return grade;
}

// Correct
public int getGrade() {
    return grade;
}

Mistake 3: Forgetting void in a setter

// Incorrect
public setGrade(int grade) {
    this.grade = grade;
}

// Correct
public void setGrade(int grade) {
    this.grade = grade;
}

Mistake 4: Setting invalid data without checking

// Weak setter
public void setGrade(int grade) {
    this.grade = grade;
}

// Better setter
public void setGrade(int grade) {
    if (grade >= 0 && grade <= 100) {
        this.grade = grade;
    }
}

17. Vocabulary

Term Meaning
Encapsulation Protecting data inside a class
Private Access modifier that limits access to inside the class
Public Access modifier that allows access from other classes
Instance Variable Variable that belongs to an object
Getter Method that returns the value of a private variable
Setter Method that changes the value of a private variable
Validation Checking if data is acceptable before using it
this Refers to the current object

18. Student-Friendly Summary

Encapsulation means keeping an object’s data private and only allowing other classes to access or change that data through methods.

Instead of doing this:

student.grade = -20;

We do this:

student.setGrade(95);
This allows the class to protect its data and prevent invalid values.

19. Practice Questions

Question 1

What does encapsulation help protect?

  1. The data inside a class
  2. The computer monitor
  3. The keyboard
  4. The package name

Answer: A

Question 2

Which access modifier is usually used for instance variables?

  1. private
  2. public
  3. static
  4. void

Answer: A

Question 3

What does a getter method usually do?

  1. Returns the value of a private variable
  2. Deletes an object
  3. Creates a new class
  4. Stops the program

Answer: A

Question 4

What does a setter method usually do?

  1. Changes the value of a private variable
  2. Prints only strings
  3. Imports a library
  4. Ends a loop

Answer: A

Question 5

Why might a setter include an if statement?

  1. To validate data before changing a variable
  2. To make the program longer
  3. To avoid using classes
  4. To create a package

Answer: A

20. Mini Coding Practice

Create a class called Car.

The class should have:

  • A private String model
  • A private int speed
  • A constructor
  • A getter for model
  • A getter for speed
  • A setter for speed
  • The setter should only allow speed values from 0 to 120

Starter Code

public class Car {
    private String model;
    private int speed;

    public Car(String model, int speed) {
        this.model = model;

        if (speed >= 0 && speed <= 120) {
            this.speed = speed;
        } else {
            this.speed = 0;
        }
    }

    public String getModel() {
        return model;
    }

    public int getSpeed() {
        return speed;
    }

    public void setSpeed(int speed) {
        if (speed >= 0 && speed <= 120) {
            this.speed = speed;
        }
    }
}

Runner

public class CarRunner {
    public static void main(String[] args) {
        Car car1 = new Car("Toyota", 55);

        System.out.println(car1.getModel());
        System.out.println(car1.getSpeed());

        car1.setSpeed(80);
        System.out.println(car1.getSpeed());

        car1.setSpeed(200);
        System.out.println(car1.getSpeed());
    }
}

Output

Toyota
55
80
80

The speed stays 80 because 200 is not allowed.