Java Encapsulation

</>Coding Tamilan.← Java course & curriculum
Java Masterclass · Lesson 30 / 50 · English

Java Encapsulation

Protect the rules around your state.

Step-by-step explanationsRunnable JavaPractice + answer

Read this topic in தமிழ் ↗.

By the end of this lesson, you can…

  • Explain the key idea behind Encapsulation.
  • Read and run a complete example, then predict what changes.
  • Recognize the topic-specific mistake discussed below.
01 / The concept

Understand the idea

Encapsulation lets an object control how its state changes. Private fields and meaningful methods can keep invalid values out. Adding getters and setters alone is not the goal; preserving a useful invariant is.

02 / Step by step

Explore the details

Encapsulation

The meaning of Encapsulation, is to make sure that "sensitive" data is hidden from users. To achieve this, you must:

  • declare class variables/attributes as private
  • provide public get and set methods to access and update the value of a private variable

Get and Set

You learned from the previous chapter that private variables can only be accessed within the same class (an outside class has no access to it). However, it is possible to access them if we provide public get and set methods.

The get method returns the variable value, and the set method sets the value.

Syntax for both is that they start with either get or set, followed by the name of the variable, with the first letter in upper case:

Example explained

The get method returns the value of the variable name.

The set method takes a parameter (newName) and assigns it to the name variable. The this keyword is used to refer to the current object.

However, as the name variable is declared as private, we cannot access it from outside this class:

If the variable was declared as public, we would expect the following output:

However, as we try to access a private variable, we get an error:

Instead, we use the getName() and setName() methods to access and update the variable:

Why Encapsulation?

  • Better control of class attributes and methods
  • Class attributes can be made read-only (if you only use the get method), or write-only (if you only use the set method)
  • Flexible: the programmer can change one part of the code without affecting other parts
  • Increased security of data
Java reference fragmentJAVA
class BankAccount {
    private double balance;  // hidden — direct access blocked

    BankAccount(double initial) { this.balance = initial; }

    public double getBalance()           { return balance; }
    public void deposit(double amount)   { if (amount > 0) balance += amount; }
    public void withdraw(double amount)  { if (amount <= balance) balance -= amount; }
}

BankAccount acc = new BankAccount(1000);
acc.deposit(500);
acc.withdraw(200);
System.out.println(acc.getBalance());  // 1300.0
// acc.balance = -9999;  // ERROR: balance is private
03 / Read and predict

A complete runnable example

This complete Main.java program focuses on the lesson idea. Reference fragments above may demonstrate individual statements; this example includes the imports, entry point, and supporting types it needs.

Main.java · complete runnable exampleJAVA
public class Main {
    public static void main(String[] args) throws Exception {
        Score score = new Score();
        score.setPoints(80);
        System.out.println(score.getPoints());
    }
}
class Score {
    private int points;
    int getPoints() { return points; }
    void setPoints(int value) {
        if (value < 0 || value > 100) throw new IllegalArgumentException("Use 0 to 100");
        points = value;
    }
}
Predict first. Then reveal the expected output / வெளியீடு
80

The output shown was checked by running this complete example. Trace the executed statements in order, then compare with your run.

04 / Learn by changing

Change it. Run it. Understand it.

Load this lesson example into the editor. Change one value or statement, predict the result, then press RUN to execute Java.

Open Java editor ↗
After the editor loads, choose Load this lesson example, then press RUN.

Powered by OneCompiler. Code you run is sent to OneCompiler for execution. For Scanner examples, supply input in the editor I/O panel; for file examples, files exist in its execution environment.

05 / Your turn

Make it your own

Practice challenge

Attempt to assign -1 using setPoints, then restore the valid value.

Reveal the answer and reasoning / விடை

The method throws IllegalArgumentException because the validation rejects a value outside 0 through 100.

One mistake to avoid: Do not bypass validation by making the field public. Keep the rule at the boundary where changes happen.

Your learning checkpoint

  • Explain the example without reading the output first.
  • Make the change requested in the practice task.
  • Describe why the result changed—or why compilation failed.

Ready to move on? Follow the next lesson in course order, or return to the curriculum to review a prerequisite.

Coding Tamilan · Understand the idea. Try the code. Build the habit.