JavaRush /Java Blog /Random EN /Principles of encapsulation in Java

Principles of encapsulation in Java

Published in the Random EN group
Hello! Let's dedicate today's lecture to encapsulation and start it right away with examples :) In front of you is a familiar soda machine. I have one question for you: how does it work? Try to answer in detail: where the glass falls out from, how the temperature is maintained inside, where the ice is stored, how the machine understands which syrup to add, etc. Most likely, you do not have answers to these questions. Well, maybe not everyone uses such machines, at the present time they are not so popular. Let's try to give another example. Something that you definitely use many times every day. Oh, there's an idea! Encapsulation Principles - 2 Explain how Google search engine works. How exactly does he search for information on the words that you entered? Why are these results at the top and not others? Even though you use Google every day, chances are you don't know it. But it is not important. After all, you don't need to know that. You can enter queries into a search engine without thinking about how it works. You can buy soda from a vending machine without knowing how it works. You can drive a car without understanding how an internal combustion engine works, and without knowing physics at all, even at the school level. All this is possible thanks to one of the main principles of object-oriented programming - encapsulation . Reading various articles on this topic, you must have come across the fact that there are two common concepts in programming - encapsulation andconcealment . And under the word "encapsulation" the authors mean one thing, then another (it just so happened). We will analyze both terms so that you have a complete understanding. The original meaning of the word “ encapsulation ” in programming is the combination of data and methods for working with this data in one package (“capsule”). In Java, the encapsulation is the . The class contains both data (class fields) and methods for working with this data. Encapsulation Principles - 3 It seems obvious to you, but in other programming concepts, everything is arranged differently. For example, in functional programming, data is strictly separated from operations on it. In OOP (object-oriented programming), programs consist of capsule classes, which are both data and functions for working with them. Now let's talk about hiding . How is it that we use all sorts of complex mechanisms without understanding how they work and what their work is based on? It's simple: their creators have provided a simple and user-friendly interface. On a soda machine, the interface is the buttons on the panel. By pressing one button, you choose the volume of the glass. By pressing the second, you choose the syrup. The third is responsible for adding ice. And that's all you need to do. It does not matter how the machine is arranged inside. The main thing is that it is designed so that the user needs to press three buttons to get soda . The same with the car. It doesn't matter what's going on inside him. The main thing is that when you press the right pedal, the car goes forward, and when you press the left pedal, it slows down . That is the essence of the cover-up. All the "insides" of the program are hidden from the user. For him, this information is superfluous, unnecessary. The user needs the end result, not the internal process. Let's take a look at the class as an example Auto:
public class Auto {

   public void gas() {

       /*some complicated things are happening inside the car
       as a result of which it goes forward*/
   }

   public void brake() {

       /*some complicated things are happening inside the car
       as a result of which it slows down*/
   }

   public static void main(String[] args) {

       Auto auto = new Auto();

       // How everything looks to the user

       //pressed one pedal - went
       auto.gas();

       //pressed another pedal - braked
       auto.brake();
   }
}
This is what implementation hiding looks like in a Java program. Everything is like in real life: the user is provided with an interface (methods). If he needs the car in the program to perform an action, just call the desired method. And what happens inside these methods is superfluous information, the main thing is that everything works as it should. Here we talked about implementation hiding . In addition to it, Java also has data hiding . We wrote about it in a lecture about getters and setters , but it will not be superfluous to recall. For example, we have a class Cat:
public class Cat {

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

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

   public Cat() {
   }

   public void sayMeow() {
       System.out.println("Meow!");
   }


}
Perhaps you remember from the last lecture what is the problem with this class? If not, let's remember. The problem is that its data (fields) are open to everyone, and another programmer can easily create an unnamed cat in the program with a weight of 0 and an age of -1000 years:
public static void main(String[] args) {

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

}
In such a situation, you can keep a close eye on whether any of your colleagues create objects with the wrong state, but it would be much better to exclude the very possibility of creating such “wrong objects”. Principles of encapsulation - 4 With the hiding of data we are helped by:
  1. access modifiers ( private , protected , package default );
  2. getters and setters.
We can, for example, put a check there to see if someone is trying to assign a negative number to a cat as an age. As we said earlier, the authors of various articles about encapsulation mean either encapsulation (combining data and methods), or hiding, or both. Both mechanisms are present in Java (this is not necessarily the case in other OOP languages), so the latter option will be the most correct. Using encapsulation gives us several important advantages:
  1. Control over the correct state of the object. Examples of this were above: thanks to the setter and the private modifier, we secured our program from cats with a weight of 0.

  2. User-friendliness through the interface. We leave "outside" for user access only methods. It is enough for him to call them to get the result, and he does not need to delve into the details of their work at all.

  3. Changes to the code do not affect users. We carry out all changes inside the methods. This will not affect the user: as he wrote auto.gas () for the car's gas, he will write it the same way. And the fact that we have changed something in the work of the gas () method will remain invisible to him: he, as before, will simply receive the desired result.
Comments
TO VIEW ALL COMMENTS OR TO MAKE A COMMENT,
GO TO FULL VERSION