eBook – Guide Spring Cloud – NPI EA (cat=Spring Cloud)
announcement - icon

Let's get started with a Microservice Architecture with Spring Cloud:

>> Join Pro and download the eBook

eBook – Mockito – NPI EA (tag = Mockito)
announcement - icon

Mocking is an essential part of unit testing, and the Mockito library makes it easy to write clean and intuitive unit tests for your Java code.

Get started with mocking and improve your application tests using our Mockito guide:

Download the eBook

eBook – Java Concurrency – NPI EA (cat=Java Concurrency)
announcement - icon

Handling concurrency in an application can be a tricky process with many potential pitfalls. A solid grasp of the fundamentals will go a long way to help minimize these issues.

Get started with understanding multi-threaded applications with our Java Concurrency guide:

>> Download the eBook

eBook – Reactive – NPI EA (cat=Reactive)
announcement - icon

Spring 5 added support for reactive programming with the Spring WebFlux module, which has been improved upon ever since. Get started with the Reactor project basics and reactive programming in Spring Boot:

>> Join Pro and download the eBook

eBook – Java Streams – NPI EA (cat=Java Streams)
announcement - icon

Since its introduction in Java 8, the Stream API has become a staple of Java development. The basic operations like iterating, filtering, mapping sequences of elements are deceptively simple to use.

But these can also be overused and fall into some common pitfalls.

To get a better understanding on how Streams work and how to combine them with other language features, check out our guide to Java Streams:

>> Join Pro and download the eBook

eBook – Jackson – NPI EA (cat=Jackson)
announcement - icon

Do JSON right with Jackson

Download the E-book

eBook – HTTP Client – NPI EA (cat=Http Client-Side)
announcement - icon

Get the most out of the Apache HTTP Client

Download the E-book

eBook – Maven – NPI EA (cat = Maven)
announcement - icon

Get Started with Apache Maven:

Download the E-book

eBook – Persistence – NPI EA (cat=Persistence)
announcement - icon

Working on getting your persistence layer right with Spring?

Explore the eBook

eBook – RwS – NPI EA (cat=Spring MVC)
announcement - icon

Building a REST API with Spring?

Download the E-book

Course – LS – NPI EA (cat=Jackson)
announcement - icon

Get started with Spring and Spring Boot, through the Learn Spring course:

>> LEARN SPRING
Course – RWSB – NPI EA (cat=REST)
announcement - icon

Explore Spring Boot 3 and Spring 6 in-depth through building a full REST API with the framework:

>> The New “REST With Spring Boot”

Course – LSS – NPI EA (cat=Spring Security)
announcement - icon

Yes, Spring Security can be complex, from the more advanced functionality within the Core to the deep OAuth support in the framework.

I built the security material as two full courses - Core and OAuth, to get practical with these more complex scenarios. We explore when and how to use each feature and code through it on the backing project.

You can explore the course here:

>> Learn Spring Security

Course – LSD – NPI EA (tag=Spring Data JPA)
announcement - icon

Spring Data JPA is a great way to handle the complexity of JPA with the powerful simplicity of Spring Boot.

Get started with Spring Data JPA through the guided reference course:

>> CHECK OUT THE COURSE

Partner – Moderne – NPI EA (cat=Spring Boot)
announcement - icon

Refactor Java code safely — and automatically — with OpenRewrite.

Refactoring big codebases by hand is slow, risky, and easy to put off. That’s where OpenRewrite comes in. The open-source framework for large-scale, automated code transformations helps teams modernize safely and consistently.

Each month, the creators and maintainers of OpenRewrite at Moderne run live, hands-on training sessions — one for newcomers and one for experienced users. You’ll see how recipes work, how to apply them across projects, and how to modernize code with confidence.

Join the next session, bring your questions, and learn how to automate the kind of work that usually eats your sprint time.

Course – LJB – NPI EA (cat = Core Java)
announcement - icon

Code your way through and build up a solid, practical foundation of Java:

>> Learn Java Basics

Partner – LambdaTest – NPI EA (cat= Testing)
announcement - icon

Distributed systems often come with complex challenges such as service-to-service communication, state management, asynchronous messaging, security, and more.

Dapr (Distributed Application Runtime) provides a set of APIs and building blocks to address these challenges, abstracting away infrastructure so we can focus on business logic.

In this tutorial, we'll focus on Dapr's pub/sub API for message brokering. Using its Spring Boot integration, we'll simplify the creation of a loosely coupled, portable, and easily testable pub/sub messaging system:

>> Flexible Pub/Sub Messaging With Spring Boot and Dapr

1. Overview

Encapsulation is an essential object-oriented programming paradigm. It allows data and methods to be grouped together in a class. However, encapsulation itself doesn’t guarantee defensive programming.

To achieve robustness, we employ information hiding. Information hiding is a programming principle that promotes the idea of restricting access to internal implementation details.

In this tutorial, we’ll explore details about encapsulation and information hiding. Additionally, we’ll see some sample code and understand the key differences between the two concepts.

2. Historical Background

The term “information hiding” was coined by Parnas in 1972 in an attempt to differentiate procedural programming from modular programming.

Parnas infers that the implementation of data should be unknown to an outside module.

Furthermore, in 1973, Zelis came up with the word encapsulation to explain how to reduce access to underlying data in a class to prevent unwanted modification.

In 1978, Parnas claimed the words encapsulation and information hiding are synonymous. However, in 2001, Paul Roger showed the difference between encapsulation and information hiding with sample code. He claimed we can have encapsulation without information hiding.

Encapsulation is a broad concept in object-oriented programming that bundles data with methods. This ensures a modular design.

Encapsulation and information hiding are sometimes used synonymously, but there are some differences.

3. Encapsulation

According to Paul Roger, encapsulation is simply bundling data with operations that act on the data.

3.1. Without Encapsulation

Let’s see an example class without encapsulation:

class Book {
    public String author;
    public int isbn;
}

Here, the Book class has public access modifiers for its fields. This makes the fields accessible from external classes.

Let’s create another class named BookDetails to get the details of a Book object:

class BookDetails {
    public String bookDetails(Book book) {
        return "author name: " + book.author + " ISBN: " + book.isbn;
    }
}

The BookDetails class contains a method that uses Book data. Here, we treat the Book class as a container for data and BookDetails as a collection of methods that act on the data.

We use a programming procedure that enforces creating an implementation class that operates on data from another class. This programming style is archaic, and it’s not modular.

Here’s a unit test to get the details of a book:

@Test
void givenUnencapsulatedClass_whenImplementationClassIsSeparate_thenReturnResult() {
    Book myBook = new Book();
    myBook.author = "J.K Rowlings";
    myBook.isbn = 67890;
    BookDetails details = new BookDetails();
    String result = details.bookDetails(myBook);
    assertEquals("author name: " + myBook.author + " ISBN: " + myBook.isbn, result);
}

The implementation above can be simplified with encapsulation. Changes in Book class affect any classes that use Book data.

3.2. With Encapsulation

Let’s improve the design in the last section using encapsulation. We can bundle the data and the methods operating on it into a single class:

class BookEncapsulation {
    public String author;
    public int isbn;
    public BookEncapsulation(String author, int isbn) {
        this.author = author;
        this.isbn = isbn;
    }
    public String getBookDetails() {
        return "author name: " + author + " ISBN: " + isbn;
    }
}

Here, we improve the code by bundling the implementation with the class. This makes the code modular. Clients can easily invoke the getBookDetails() methods without having much knowledge of its implementation.

Let’s see a unit test to invoke getBookDetails():

@Test
void givenEncapsulatedClass_whenDataIsNotHidden_thenReturnResult() {
    BookEncapsulation myBook = new BookEncapsulation("J.K Rowlings", 67890);
    String result = myBook.getBookDetails();
    assertEquals("author name: " + myBook.author + " ISBN: " + myBook.isbn, result);
}

Encapsulation improves the code, but external classes can modify the Book data because the fields use a public access modifier. However, encapsulation doesn’t have strict rules on which access modifier to use. We can use the public, private,  and protected access modifiers.

Additionally, encapsulation helps introduce a feature to a class without breaking external code using the class. Let’s modify the BookEncapsulation class by introducing an id:

// ...
public int id = 1;
public BookEncapsulation(String author, int isbn) {
    this.author = author;
    this.isbn = isbn;
}
public String getBookDetails() {
    return "author id: " + id + " author name: " + author + " ISBN: " + isbn;
} 
// ...

Here, we introduce the id field and modify the return details of getBookDetails(). These internal changes won’t break any client code. This makes encapsulation powerful and modular.

However, we can make encapsulation more strict by applying the idea of “information hiding”. Encapsulation isn’t enough for defensive programming. We need to apply information hiding with encapsulation to prevent unwanted data modification.

4. Information Hiding

Information hiding is a programming principle that aims to prevent the direct modification of the data of a class. Also, it provides a strict guideline to access and modify the data of a class.

Additionally, it helps to hide design implementations from the client, especially design implementations that are likely to change.

Furthermore, information hiding when used with encapsulation ensures modular code.

Let’s improve the encapsulated class by applying information hiding:

class BookInformationHiding {
    private String author;
    private int isbn;
    private int id = 1;
    
    public BookInformationHiding(String author, int isbn) {
        setAuthor(author);
        setIsbn(isbn);
    }
    public String getAuthor() {
        return author;
    }
    public void setAuthor(String author) {
        this.author = author;
    }
    public int getIsbn() {
        return isbn;
    }
    public void setIsbn(int isbn) {
        this.isbn = isbn;
    }
    public String getBookDetails() {
        return "author id: " + id + " author name: " + author + " ISBN: " + isbn;
    }
}

Here, we use the private access modifier to restrict access and altering of fields from an external class. Furthermore, we create getters and setters to set how the field can be accessed and modified.

In contrast to encapsulation without information hiding, where any access modifier can be used, information hiding is implemented through the use of a private access modifier. This restricts access to the fields within the class only.

The fields cannot be directly accessed from a client code, thus making it more robust.

Let’s see a unit test for the modified class:

@Test
void givenEncapsulatedClass_whenDataIsHidden_thenReturnResult() {
    BookInformationHiding myBook = new BookInformationHiding("J.K Rowlings", 67890);
    String result = myBook.getBookDetails();
    assertEquals("author id: " + 1 + " author name: " + myBook.getAuthor() + " ISBN: " + myBook.getIsbn(), result);
}

Additionally, we can create a strict rule on how data can be modified. For instance, we can avoid a negative ISBN by modifying the setter:

public void setIsbn(int isbn) {
    if (isbn < 0) {
        throw new IllegalArgumentException("ISBN can't be negative");
    }
    this.isbn = isbn;
}

Here, we create a strict rule on how to modify the ISBN.

5. Key Differences

Here’s a summary table showing the key differences between encapsulation and information hiding:

Information Hiding Encapsulation
A design principle to hide implementation details and unintended modification to data An object-oriented principle that bundles data with functions operating on them.
Strictly uses the private access modifier Not strict on access modifiers and can use a public, private, or protected access modifier
Helps to achieve defensive programming A methodology to achieve information-hiding

6. Conclusion

In this article, we learned the key concepts of encapsulation and information hiding. Additionally, we saw an example code that shows the slight differences between encapsulation and information hiding.

However, a school of thought claims information hiding and encapsulation are synonymous. We need to always apply the principles of information hiding when encapsulating a class.

The code backing this article is available on GitHub. Once you're logged in as a Baeldung Pro Member, start learning and coding on the project.
Baeldung Pro – NPI EA (cat = Baeldung)
announcement - icon

Baeldung Pro comes with both absolutely No-Ads as well as finally with Dark Mode, for a clean learning experience:

>> Explore a clean Baeldung

Once the early-adopter seats are all used, the price will go up and stay at $33/year.

eBook – HTTP Client – NPI EA (cat=HTTP Client-Side)
announcement - icon

The Apache HTTP Client is a very robust library, suitable for both simple and advanced use cases when testing HTTP endpoints. Check out our guide covering basic request and response handling, as well as security, cookies, timeouts, and more:

>> Download the eBook

eBook – Java Concurrency – NPI EA (cat=Java Concurrency)
announcement - icon

Handling concurrency in an application can be a tricky process with many potential pitfalls. A solid grasp of the fundamentals will go a long way to help minimize these issues.

Get started with understanding multi-threaded applications with our Java Concurrency guide:

>> Download the eBook

eBook – Java Streams – NPI EA (cat=Java Streams)
announcement - icon

Since its introduction in Java 8, the Stream API has become a staple of Java development. The basic operations like iterating, filtering, mapping sequences of elements are deceptively simple to use.

But these can also be overused and fall into some common pitfalls.

To get a better understanding on how Streams work and how to combine them with other language features, check out our guide to Java Streams:

>> Join Pro and download the eBook

eBook – Persistence – NPI EA (cat=Persistence)
announcement - icon

Working on getting your persistence layer right with Spring?

Explore the eBook

Course – LS – NPI EA (cat=REST)

announcement - icon

Get started with Spring Boot and with core Spring, through the Learn Spring course:

>> CHECK OUT THE COURSE

Partner – Moderne – NPI EA (tag=Refactoring)
announcement - icon

Modern Java teams move fast — but codebases don’t always keep up. Frameworks change, dependencies drift, and tech debt builds until it starts to drag on delivery. OpenRewrite was built to fix that: an open-source refactoring engine that automates repetitive code changes while keeping developer intent intact.

The monthly training series, led by the creators and maintainers of OpenRewrite at Moderne, walks through real-world migrations and modernization patterns. Whether you’re new to recipes or ready to write your own, you’ll learn practical ways to refactor safely and at scale.

If you’ve ever wished refactoring felt as natural — and as fast — as writing code, this is a good place to start.

eBook Jackson – NPI EA – 3 (cat = Jackson)