Table of Contents
Share this Resource

What is Encapsulation in Java?

Overview

1. Encapsulation combines data and related methods within a Java class.
2. Access modifiers control the visibility of class members.
3. Private fields and public methods can provide controlled data access.
4. Getters, setters and validation help manage an object's internal state.
5. Encapsulation supports data integrity, maintainability and modular design.

Encapsulation in Java is one of four core concepts available in Object-oriented Programming (OOP) languages. The four OOP concepts are abstraction, inheritance, polymorphism and encapsulation. These concepts make OOP languages like Java extremely popular among Developers. Java’s features, like platform independence, robustness and security, make it popular worldwide among Developers.

Its popularity is thanks to its object-oriented concepts like encapsulation, providing Developers various benefits. Read this blog to learn about encapsulation in Java, its advantages, and the benefits of encapsulation. Let’s dive in to learn more!

What is Encapsulation in Java?

Encapsulation in Java is a fundamental OOP concept that restricts direct access to an object's data by bundling variables and methods within a class. It supports data protection through access modifiers, such as private fields, and methods that provide controlled access or modification while maintaining code flexibility and reusability.

Java Training

How Does Encapsulation Work in Java?

Encapsulation works by separating an object's internal data from the code that interacts with it. The class controls which information can be accessed and how its values can change. The following concepts help implement encapsulation in Java.

1) Private Fields and Controlled Access

Private fields store an object's internal data and restrict direct access from outside the enclosing class. For example, when a bank account's balance is declared private, unrelated classes cannot directly assign a new value to it. Instead, they must use the operations that the BankAccount class makes available. This allows the class to apply rules before changing its internal state.

2) Getter and Setter Methods

Getter and setter methods are commonly used to provide controlled access to private fields.

a) Getter Methods: Return the value of a field, such as getName() or getSalary().

b) Setter Methods: Update the value of a field, such as setName() or setSalary().

However, not every private field needs both methods. Access should depend on the class's requirements.

Trainer Insight

Encapsulation is about protecting an object's internal state, not automatically generating getters and setters for every field. Giving external code unrestricted access through setters can reduce the protection that encapsulation is intended to provide.

Access Modifiers

Access modifiers are used to limit the access of data within a class only to a certain degree. The level of access and privacy imposed on the class depends on the type of access modifier used in a program. Java has four access levels, including three explicit access modifiers and package-private access, which are as follows:

1) Public

The public access modifier provides the widest level of access in Java programming. Any data, method or class declared public can generally be accessed from anywhere, whether within the same class or outside the class, provided the declaring class and package are accessible. It is accessible to both classes within the package it was declared in and outside the package. The keyword for the public access modifier is public, and it has the widest scope out of all access modifiers.

2) Protected

The protected access modifier can be applied to fields, methods, and constructors but not to top-level classes. It allows access within the same package and also in subclasses, even if they are in different packages. This makes it particularly useful for inheritance, enabling child classes to access protected members of their parent class while still restricting direct access from non-subclassed external classes.

3) Default

Default access, also known as package-private access, allows classes and members to be accessed within the same package but restricts access from other packages. This access level applies when no explicit access modifier is specified.

4) Private

The private access modifier restricts access to fields, methods, and inner (nested) classes, ensuring that they are accessible within the enclosing top-level class and its permitted nested classes. It cannot be applied to top-level classes. private is commonly used for data hiding and encapsulation, preventing direct modification of class members from outside the permitted scope and supporting controlled access through methods when necessary.

Access Modifier

Learn how to create applications, solve complex problems and bring your ideas to life through code. Sign up for the Java Programming Course now!

Encapsulation in Java Examples

Here are a few examples of encapsulation in a Java program. Following the first example, you’ll start by declaring a public class Employee. As you declare three variables within the said class, “name”, “age”, and “salary”. You will use setter methods to assign values to those respective variables.

1) Read and Write Program

Java Program Example 1: Here in this Java program, you’ll find the use of three setter methods declared, namely setName(), setAge() and setSalary() methods. These setter methods allow values to be assigned to the class's private fields without accessing them directly from outside the class. To read those values and print out the output, we’ll use the getter method in the program. Here you should use the getName(), getAge() and getSalary() methods to get the output in a separate class EncapsulationDemo.

Read and Write Program in Java

Output:

Read and Write Program Output

Java Program Example 2: Here is another program demonstrating encapsulation in Java. In this Java program, a rectangle class has two instance variables, length and width. These variables are declared private; hence, they can only be accessed or modified by using getter and setter methods. In this case, you will find the use of getLength() and getWidth() getter methods, as well as setLength() and setWidth() setter methods, respectively.

The getArea() method in the program uses the mathematical formula of an area of a rectangle. The Java program uses previously declared variables for length and width as respective values. Finally, we print out our statement using the System.out.println() method in Java.

Read and Write Program in Java

Output:

Read and Write Program Output

2) Read-only Program

Java Program Example 3: Let's see an example of a Read-only encapsulated program, which provides access to an object's data without exposing public methods for modifying it. A read-only interface does not necessarily make an object immutable. True immutability requires ensuring that the object's state cannot change after construction. In Java, this can be achieved through appropriate design, such as using private final fields, preventing unwanted state changes and protecting mutable data.

In this program, you will need to declare a class, such as, a Car class. You'll need to declare some variables within that class; in this instance, they are make, model and year. You will need to use methods to display and print the values of these variables. Here, the methods are getMake(), getModel(), and getYear(). As you will see, this program does not use any setter methods, so you can get the output but cannot modify the fields through public setter methods.

Read-only Program in Java

Output:

Read-only Program in Java Output

3) Write-only Program

Java Program Example 4: Lastly, you will see an example of a write-only encapsulation program. In this case, the class BankAccount has the variable balance declared within it. Later in the Main class, you’ll need to create an instance of the BankAccount class. Lastly, you’ll need to use methods to rewrite or initialise the variable’s value.

In this Java program, you’ll use setBalance() as a setter method to assign or update the value of the balance variable. A write-only class exposes a method for modifying data without providing a corresponding getter. This approach may be useful in certain situations, although meaningful operations such as deposit() and withdraw() are generally more appropriate for a bank account.

In this example, the balance is updated through the setter method, but no output appears because the program does not include a statement to display the value.

Write-only Program in Java

Output: This program will have no output, being a write-only class.

Benefits of Encapsulation in Java

Encapsulation in Java, a crucial concept for effective real-time programming, offers several key benefits. Let's explore some of them:

1) Control Over Data: Classes gain greater control over access to their data members and the operations that modify them. This control helps maintain data integrity and prevent unintended modifications when appropriate validation is applied.

2) Data Hiding: Restricts direct access to internal data and implementation details, helping prevent unintended dependencies and reducing the likelihood of errors when the implementation changes.

3) Flexible Data Access: Enables setting class variables as read-only or write-only, tailored to specific requirements. This flexibility helps control how other parts of a program interact with an object's data.

4) Code Reusability: Encapsulation facilitates the reuse of existing code, saving time and resources in developing new applications.

5) Ease of Modification: It makes updating existing code more straightforward and less error-prone. This is essential for maintaining and scaling complex software systems.

6) Simplified Testing: Encapsulation can support unit testing by providing clearly defined methods and controlling interactions with an object's internal state. However, testing still depends on the class design and the accessibility of its behaviour.

7) Reduced Dependencies: Encapsulation reduces unnecessary dependencies on a class's internal implementation. This allows Developers to modify internal details without affecting other parts of the program, provided the public interface remains compatible.

Become a Web Developer with the power of Java! Sign up for the Web Development Using Java Training now!

Best Practices for Encapsulation in Java

Following best practices help developers use encapsulation effectively without making classes unnecessarily complicated.

1) Keep Internal Fields Private: Declare fields as private unless there is a specific reason to use another access level. This helps prevent external code from depending on internal implementation details.

2) Expose Only Necessary Methods: Provide getters, setters and other public methods only when they are needed. Avoid exposing information or operations that other classes do not require.

3) Validate Data Before Modification: Apply appropriate validation before updating an object's state. For example, a bank account should reject invalid transaction amounts and prevent withdrawals that violate its rules.

4) Prefer Meaningful Operations: Instead of allowing external code to assign any balance through setBalance(), consider methods such as deposit() and withdraw(). These operations can enforce business rules while managing changes.

5) Protect Mutable Data: When a private field refers to a mutable object, avoid exposing it directly if doing so would allow callers to modify the object's internal state. Use defensive copies or suitable read-only views where necessary.

This is how you determine whether a field should have a getter, a setter, both or neither:

How to Choose the Right Access Method in Java?

Choosing the Right Access Method in Java

So, encapsulation in Java is an essential OOP principle that helps Developers organise data and behaviour while controlling access to an object's internal state. Understanding how to implement encapsulation, validate data and expose only necessary operations will help you write cleaner Java code and apply object-oriented programming principles more effectively.

Nilotpal Sarmah
Nilotpal Sarmah

Senior Content Writer

Nilotpal Sarmah is a Senior Content Writer with 11+ years of overall experience spanning engineering, operations and content development. His technical knowledge and extensive writing experience enable him to simplify specialised topics across IT and Tech, Business Skills, Project Management, Health and Safety, and ISO and Compliance.

View Detail icon
cross

BIGGEST HALLOWEEN SALE!

halloween-sale GET UPTO 40% OFF!

* WHO WILL BE FUNDING THE COURSE?

close

close

Thank you for your enquiry!

One of our training experts will be in touch shortly to go over your training requirements.

close

close

Press esc to close

close close

Back to course information

Thank you for your enquiry!

One of our training experts will be in touch shortly to go overy your training requirements.

close close

Thank you for your enquiry!

One of our training experts will be in touch shortly to go over your training requirements.