CodeGym/Java Blog/OOP Java/Encapsulation in Java
Milan Vucic
Programming Tutor at

Encapsulation in Java

Published in the OOP Java group
Hi! We'll devote today's lesson to Encapsulation in Java and begin with examples right out of the gate:) Here you have an ordinary soda dispensing machine. I've got one question for you: how does it work? Try to give a detailed answer: Where does the soda come from? How is the internal temperature maintained? Where is the ice stored? How does the machine know which syrup to add? You probably don't have answers to these questions. Okay, maybe not everyone uses these machines. They aren't that popular at present. Let's try another example. Something you definitely use many times everyday. Oh, I have an idea! Principles of encapsulation - 2Tell me how the Google search engine works. How exactly does it search for information on the words you enter? Why are these results at the top and not others? Even though you use Google everyday, you probably don't know. But that doesn't matter. After all, it's not something you need to know. You can use a search engine without thinking about exactly how it works. You can buy soda from a machine without knowing how it's built. You can drive a car without delving into how the internal combustion engine works and without even knowing high-school physics. This is all possible thanks to one of the main principles of object-oriented programming: encapsulation. In reading different articles on the topic, you must have encountered two widespread programming concepts: encapsulation and information hiding. As it happens, different people understand the word 'encapsulation' to mean different things. We'll decipher both terms so you have a complete understanding. In programming, the original meaning of encapsulation was combining data and methods for working with that data in one package ("capsule"). In Java, encapsulating package is the class. The class contains both data (fields) and methods for working with that data. Principles of encapsulation - 3This may seem obvious to you, but everything is arranged differently in other programming paradigms. For example, in functional programming, data is strictly separated from data operations. In object-oriented programming (OOP), programs consist of capsules (classes) consisting of both data and functions for working with data.

Now let's talk about information hiding

How do we use all sorts of complex mechanisms without understanding how they're built or how they work? It's simple: their creators provided simple and convenient interfaces. On a soda machine, the interface is the buttons on the front panel. One button lets you choose the cup size. You choose the syrup with a second button. A third is responsible for adding ice. And that's all you need to do. It doesn't matter what the machine looks like inside. The important thing is that it's designed so that the user gets soda by pushing three buttons. The same thing applies to a car. It doesn't matter what's going on inside. The important thing is that when you press the right pedal the car moves forward, and when you press the left pedal the car slows down. This is the essence of information hiding. All of a program's 'innards' are hidden from the user. Such information is superfluous or unnecessary for the user. The user needs an end result, not an internal process. For an example, let's take a look at the Vehicle class:
public class Vehicle {

   public void gas() {

       /* Some complicated things happen inside a car.
       As a result, it moves forward */

   public void brake() {

       /* Some complicated things happen inside a car.
       As a result, it slows down */

   public static void main(String[] args) {

       Vehicle vehicle = new Vehicle();

       // How everything looks to the user

       // Press one pedal, the car moves

       // Press the other pedal, the car brakes
This is how the implementation is hidden in a Java program. Just like in real life: the user is provided with an interface (methods). In a program, if you need a car to perform an action, you simply call the desired method. What happens inside these methods is superfluous. What matters is that everything works as it should. Here we've been talking about implementation hiding. Java also has data hiding. We wrote about it in the lesson about getters and setters, but a reminder won't hurt. For example, we have a Cat class:
public class Cat {

   public String name;
   public int age;
   public int weight;

   public Cat(String name, int age, int weight) { = name;
       this.age = age;
       this.weight = weight;

   public Cat() {

   public void sayMeow() {

Maybe you remember from a past lesson what the problem is with this class? If not, let's recall. The problem is that its data (fields) are open to everyone. Another programmer could easily create a nameless cat with a weight of 0 and age of -1000 years:
public static void main(String[] args) {

   Cat cat = new Cat(); = "";
   cat.age = -1000;
   cat.weight = 0;

In this situation, you could carefully track whether one of your colleagues is creating objects with invalid state, but it would be much better to eliminate even the possibility of creating these invalid objects. Principles of encapsulation - 4We achieve data hiding with the help of:
  1. access modifiers (private, protected, package default);
  2. getters and setters.
We use them to check if someone is trying to give the cat a negative age. As we said earlier, the authors of various articles on encapsulation are actually referring to encapsulation (combining data and methods) or information hiding, or both. Java has both mechanisms (this is not necessarily the case in other OOP languages), so the last option is most correct.

Encapsulation gives us several important advantages:

  1. Monitoring correct object state. We gave examples of this above: thanks to the setter and private modifier, we've secured our program against cats with a weight of 0.

  2. User-friendly interface. We leave only methods exposed to the user. The user simply needs to call them to get a result. And there's no need whatsoever to delve into the details of how they work.

  3. Code changes don't affect users. We make all changes inside of methods. This doesn't affect users: they wrote vehicle.gas() to apply the gas, and that's what they will keep on doing. The fact that we changed something inside the gas() method remains invisible: as before, they simply get the required result.
Comments (22)
  • Popular
  • New
  • Old
You must be signed in to leave a comment
Aldo Luna Bueno
Level 28 , Peru
22 February 2022, 18:59
En Java, la encapsulación se manifiesta en dos aspectos: las cápsulas y el ocultamiento de información (datos y métodos). 1. Cápsulas Son las clases y agrupan la información de una forma especial: juntando datos y métodos. 2. Ocultamiento de información Se divide en dos: ocultamiento de implementación y ocultamiento de datos. a. Ocultamiento de implementación La implementación de instrucciones se oculta dentro de paquetes que conocemos como métodos, de forma que se pueden ejecutar esas instrucciones simplemente sabiendo el nombre del método que las agrupa. b. Ocultamiento de datos Oculta y protege los datos para que ningún cambio los vuelva inválidos. Se logra combinando modificadores de acceso y métodos getter y setter.
Level 15 , Poland, Poland
23 July 2022, 16:22
I read a few articles and got maybe 20 percent, but you wrote a few lines and I understand everything. Thank you:)
Aldo Luna Bueno
Level 28 , Peru
24 July 2022, 04:30
It's the first time I've been told this around here, ha ha. I am very glad that it served you. If you have any questions, happy to help you.
Level 20 , 泾县, China
11 March 2021, 12:36
encapsulation 封装
Chang You
Level 47 , Santa Rosa, United States
24 December 2020, 16:29
Chandan Thapa
Level 22 , Dubai, United Arab Emirates
11 November 2020, 16:32
Im getting the hang of it finally, after repeated readings on OOP
Karas Java Developer
10 November 2020, 01:44
What if the method we call does things additionally to what its supposed to do? For example as above, we use the .gas() method, the car moves forward but the method was also programmed to decreaseFuel(); or something like that. I do not want that to happen but is included with the class. What do you do? Write another similar class? can you un-inherit something? Just my two cents. and my question.
Jonaskinny Java Developer at Sandmedia
24 February 2022, 19:08
If you can override the parent method, you remove the parent functionality for that method. See PolyMorphism and the use of super.methodname()
Kou Shikyo
Level 20 , Tokyo
5 October 2020, 05:57
Hiding things from user to protect our code .Dont make things complex
Level 22
31 July 2020, 08:31
I don't really understand in fact. The user will not have to write vehicule.gas() anyway, because it would have an application interface, with only what we wants to show him. So encapsulation is more like hiding things from ourselves, no?
22 August 2020, 21:08
Yes, because as a programmer you will wear different hats. When you are wearing the "implementation" hat you will code the class internals, but then you will put on "application" hat and write the app using the classes you just implemented. You don't want to think of the implementation at that point and just treat it as a "black box".
Ian De Bie Full Stack Developer
27 July 2020, 21:37
is there an example of a method where the inside is NOT hidden? i mean when you use a method in your code like string.toLowerCase() is that hidden or do they mean something else? it's not clear to me what they mean by hidden. if you make a method private is that hidden, and if so then it goes against the statement made that users use a method and don't need to know how it works, so if it's private then they can't use it. so to me, it seems like every method is used by user and they don't need to know how it works on the inside. my point is what methods are there that you DO have to know how it works? this whole thing confuses me because I feel like encapsulation is this big mysterious topic, but all I really get out of it is that all methods are encapsulated naturally so what is the point of describing encapsulation in the first place if they all have the same behavior. I must be totally missing something so if anyone gets my point and can explain what I am missing, then that would be really helpful.
Jonaskinny Java Developer at Sandmedia
24 February 2022, 19:18
If the method of a class is hidden, and your class uses this class, your class (assuming its not in the same package as the class with the hidden method) will never even know about the method. This is the basic notion of interface programming. Encapsulation is rather simple as you suggest. I think you may be over-thinking it in this case, and resources outside CG like the Sun tutorial map will give you a much clearer understanding. Essentially hidden methods of class A are private methods of class A. Encapsulation is a means to describe the use of private methods & variables within class A, so objects of type A and only type A can access them. If A needs other classes to influence values/behavior contained in these private methods &/or variables in order to make A useful to those classes, it needs to provide access via non-private methods &/or variables, to enable that influence, while gate-keeping what actually happens inside A to those private variables. We all have minds, others plant ideas in our heads through our ears (interface method) but we dont let them open our skulls and stuff the idea into our grey matter. That is private (hidden, encapsulated) work that we do on our own minds, using other parts of our own minds, while we process (or dont process) what they put in our ears.
Level 20 , Poland
12 July 2020, 08:15
not to confuse field hiding with data encapsulation. field hiding is to declare the same name of field in subclass as in superclass so a superclass field is hidden - almost always a sign of bad code. data encapsulation hiding class fields with private modifier and accessing it only through publicly exposed accessor methods
Peter Schrijver
Level 23 , Hilversum, Netherlands
16 June 2020, 09:40
very useful