Understanding Encapsulation Using Examples

In this lesson, you will get a firmer understanding of encapsulation in Java with the help of examples.

We'll cover the following

Encapsulation refers to the concept of binding data and the methods operating on that data in a single unit also called a class.

The goal is to prevent this bound data from any unwanted access by the code outside this class. Let’s understand this using an example of a very basic User class.

Consider that we are up for designing an application and are working on modeling the log in part of that application. We know that a user needs a username and a password to log into the application.

A very basic User class will be modeled as:

  • Having a field for the userName
  • Having a field for the password
  • A method named login() to grant access

Whenever a new user comes, a new object can be created by passing the userName and password to the constructor of this class.

Get hands-on with 1000+ tech skills courses.