Java Encapsulation

What is Encapsulation?

Encapsulation is the process of hiding data and controlling access to it.

This is done using private variables and public methods.

Loading...
Output:

Getters and Setters

Use getters to access data and setters to modify it.

Loading...
Output:

Using Encapsulation

Loading...
Output:

Controlling Data

Setters can include validation logic.

Loading...
Output:

Why Not Public Variables?

Loading...
Output:

Practice

Create a BankAccount class with controlled balance access.

Loading...
Output:

Need Help?